Created
December 23, 2014 03:48
-
-
Save binux/2e1c7b3b2b8de18f950c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 threading | |
import tornado | |
import tornado.httpserver | |
import tornado.websocket | |
wss = [] | |
class WSHandler(tornado.websocket.WebSocketHandler): | |
def check_origin(self, origin): | |
return True | |
def open(self): | |
print ('New connection established.') | |
if self not in wss: | |
wss.append(self) | |
def on_message(self, message): | |
print ('Received message: %s' % message) | |
write_data(message) | |
def on_close(self): | |
print ('Connection closed.') | |
if self in wss: | |
wss.remove(self) | |
class Application(tornado.web.Application): | |
def __init__(self): | |
settings = dict( | |
debug = True, | |
) | |
super(Application, self).__init__([ (".*", WSHandler), ], **settings) | |
application = Application() | |
def write_data(message): | |
for ws in wss: | |
print ("Sending: %s" % message) | |
ws.write_message(message); | |
class ServerThread(threading.Thread): | |
def run(self): | |
print ("Starting server.") | |
http_server = tornado.httpserver.HTTPServer(application) | |
http_server.listen(4044) | |
main_loop = tornado.ioloop.IOLoop.instance() | |
main_loop.start() | |
def send_data(self, message): | |
write_data(message); | |
server_thread = ServerThread() | |
server_thread.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment