Start a websocket server with tornado

import tornado.ioloop
import tornado.web
import tornado.escape
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.options
import time
import logging
import uuid
import sys,os
from tornado.options import define, options



class MainHandler(tornado.web.RequestHandler):
	def get(self):
		self.write("Hello, world")

def make_app():
	return tornado.web.Application([
		(r"/", MainHandler),
	])



define('port', default=8889, help="The tornado server port", type=int)


class WebSocketSever(tornado.websocket.WebSocketHandler):
	bao_cons = set()
	bao_waiters = {}
	global con_key
	global token

	# def initialize(self, my_object):
	# 	self.my_object = my_object

	def open(self):
		sole_id = str(uuid.uuid4()).upper()
		print(sole_id)
		self.con_key = sole_id
		self.token = self.get_argument("token")
		self.bao_waiters["{}".format(sole_id)] = self
		self.bao_cons.add(self)
		# self.write_message({"websocket_sole_id": sole_id})
		self.write_message({"token": self.token})
		logging.info("websocket opened!")
		print(self.bao_cons)

	def on_message(self, message):

		print(type(message))
		if message == "close":
			self.close()
			return
		try:
			parse_data = tornado.escape.json_decode(message)
			if parse_data["user"] and parse_data["content"]:
				user = parse_data["user"]
				content = parse_data["content"]
				if not user or not content:
					logging.info("Date is wrong!")
					return
				else:
					for key in self.bao_waiters.keys():
						if key == user:
							try:
								self.bao_waiters[key].write_message("{}".format(content))
							except Exception as e:
								logging.info(e)
							finally:
								logging.info("process finished!")
		except:
			for con in self.bao_cons:
				con.write_message(message)

	def check_origin(self, origin: str):
		return True

	def allow_draft76(self):
		return True

	def on_close(self):
		self.bao_cons.remove(self)
		# self.bao_waiters.pop(self.con_key)
		self.bao_waiters.pop(self.token)

		logging.info("websocket closed!")
		print(self.bao_cons)


class Application(tornado.web.Application):
	def __init__(self, handlers, setting):
		super(Application, self).__init__(handlers, **setting)


def main():
	options.parse_command_line()
	handlers = [
		(r"/websocket", WebSocketSever),
		(r"/http", MainHandler),
	            ]
	setting = dict(xsrf_cookies=False)
	app = Application(handlers, setting)
	print(options.port)

	app.listen(options.port)
	tornado.ioloop.IOLoop.current().start()


if __name__ == "__main__":
	# app = make_app()
	# app.listen(8889)
	# tornado.ioloop.IOLoop.current().start()
	main()

then to access the websocket server, for example, using javascript

var ws = new WebSocket("ws://127.0.0.1:8080/api/v1/namespaces/default/services/serices:8889/proxy/websocket?token=123");
ws.onopen = function() {
   ws.send("Hello, world");
};
ws.onmessage = function (evt) {
   alert(evt.data);
};

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s