Skip to content

Instantly share code, notes, and snippets.

@binux
Created December 23, 2014 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binux/2e1c7b3b2b8de18f950c to your computer and use it in GitHub Desktop.
Save binux/2e1c7b3b2b8de18f950c to your computer and use it in GitHub Desktop.
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