Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- '''
- Created on Jun 21, 2018
- @author: eaibot
- '''
- from tornado.websocket import WebSocketHandler
- from threading import Lock
- from tornado import ioloop, web, gen
- import json
- class WsHandler(WebSocketHandler):
- client_id=0
- clients_connected=0
- wsClients = set()
- cmdWsId = ""
- clientCons = {}
- def __init__(self , application, request, **kwargs):
- super(WsHandler, self).__init__(application, request, **kwargs)
- self.handler_lock = Lock()
- def open(self):
- self.__class__.wsClients.add(self)
- self.__class__.client_id +=1
- self.__class__.clients_connected +=1
- print("client %d connected ..."%(self.__class__.client_id))
- def on_message(self, message):
- self.reqMsg=json.loads(message)
- self.reqType=self.reqMsg.get("type")
- self.__class__.clientCons[self.reqType]=self
- ioloop.IOLoop.current().spawn_callback(self.doWithData, self.reqType)
- @gen.coroutine
- def doWithData(self, type):
- msg="aaaaaaaaaaaaaaaaasssssssssssssssssssssssssssssssssszdfswfdw2222222222222222222222rf5666666666666666666666666666tfgj7777777777ujjhh999999999jhht000000000000000000000"
- while self in self.__class__.wsClients:
- yield gen.sleep(0.2)
- yield self.send_message(self.reqType, msg)
- def on_close(self):
- self.__class__.wsClients.remove(self)
- self.__class__.clients_connected -= 1
- print("client disconnected, %d clients still linked ..."%(self.__class__.clients_connected))
- def check_origin(self, origin):
- return True
- @gen.coroutine
- def send_message(self, req_type, message):
- with self.handler_lock:
- returnJson = {"type":req_type, "result":message}
- jsonStr = json.dumps(returnJson)
- try:
- self.write_message(jsonStr)
- except Exception as exc :
- print("%s : %s"%(req_type , exc))
- if __name__ == '__main__':
- application=web.Application([
- (r"/", WsHandler),
- ])
- application.listen(8888)
- ioloop.IOLoop.current().start()
Add Comment
Please, Sign In to add comment