Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
tornado_websocket
import logging
import tornado.escape
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
from tornado.options import define, options
from tornado.httpserver import HTTPServer
define("port", default=8888, help="run on the given port", type=int)
# queue_size = 1
# producer_num_items = 5
# q = queues.Queue(queue_size)
def isPrime(num):
"""
Simple worker but mostly IO/network call
"""
if num > 1:
for i in range(2, num // 2):
if (num % i) == 0:
return ("is not a prime number")
else:
return("is a prime number")
else:
return ("is not a prime number")
class Application(tornado.web.Application):
def __init__(self):
handlers = [(r"/chatsocket", TornadoWebSocket)]
super(Application, self).__init__(handlers)
class TornadoWebSocket(tornado.websocket.WebSocketHandler):
clients = set()
# enable cross domain origin
def check_origin(self, origin):
return True
def open(self):
TornadoWebSocket.clients.add(self)
# when client closes connection
def on_close(self):
TornadoWebSocket.clients.remove(self)
@classmethod
def send_updates(cls, producer, result):
for client in cls.clients:
# check if result is mapped to correct sender
if client == producer:
try:
client.write_message(result)
except:
logging.error("Error sending message", exc_info=True)
def on_message(self, message):
try:
num = int(message)
except ValueError:
TornadoWebSocket.send_updates(self, "Invalid input")
return
TornadoWebSocket.send_updates(self, isPrime(num))
def start_websockets():
tornado.options.parse_command_line()
app = Application()
server = HTTPServer(app)
server.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
start_websockets()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.