Created
November 9, 2015 08:46
-
-
Save lethee/f1f0d9ff8a034b0866ee to your computer and use it in GitHub Desktop.
Python UTC current Time in milleseconds with non-block TCP Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import select | |
import datetime | |
port = 20001 | |
def main(): | |
serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
serversock.setblocking(0) | |
serversock.bind(('0.0.0.0', port)) | |
serversock.listen(5) | |
inputs = [ serversock ] | |
outputs = [] | |
while inputs: | |
print "> wait next events" | |
readable, writable, exceptional = select.select(inputs, outputs, inputs) | |
for s in readable: | |
if s is serversock: | |
connection, client_address = s.accept() | |
connection.setblocking(0) | |
outputs.append(connection) | |
print "> accept", connection | |
for s in writable: | |
print "> send", connection | |
s.send(str(getCurrentTimeInMilli())) | |
outputs.remove(s) | |
print "> close", connection | |
s.close() | |
def getCurrentTimeInMilli(): | |
utcnow = datetime.datetime.utcnow() | |
delta = utcnow - datetime.datetime.combine(utcnow.date(), datetime.time(0)) | |
return delta.seconds * 1000 + utcnow.microsecond / 1000 | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment