Skip to content

Instantly share code, notes, and snippets.

@jonathan-daniel
Created November 17, 2016 13:37
Show Gist options
  • Save jonathan-daniel/6d53cf6b26c46996bb0ad27ab8e7d7a7 to your computer and use it in GitHub Desktop.
Save jonathan-daniel/6d53cf6b26c46996bb0ad27ab8e7d7a7 to your computer and use it in GitHub Desktop.
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.gen
import time
from tornado import gen
from threading import Thread
connections = set()
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def initialize(self):
print 'Websocket opened'
def open(self):
print 'New connection'
connections.add(self)
self.write_message('test')
def on_message(self, message):
print message
def on_close(self):
connections.remove(self)
print 'Connection closed'
def write_message(self, message):
print ("Sending: ", message)
def test(self):
self.write_message("scheduled!")
def make_app():
return tornado.web.Application([
(r'/ws', WebSocketHandler),
])
def read_function():
while True:
time.sleep(5) # a while loop to simulate the reading
print 'read serial'
str = 'string to send'
[client.write_message(str) for client in connections]
if __name__ == '__main__':
thread = Thread(target = read_function)
application = make_app()
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
thread.start()
tornado.ioloop.IOLoop.instance().start()
thread.join()
print 'test'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment