Guest User

Untitled

a guest
Dec 16th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. '''
  4. Created on Jun 21, 2018
  5. @author: eaibot
  6. '''
  7. from tornado.websocket import WebSocketHandler
  8. from threading import Lock
  9. from tornado import ioloop, web, gen
  10. import json
  11.  
  12. class WsHandler(WebSocketHandler):
  13. client_id=0
  14. clients_connected=0
  15. wsClients = set()
  16. cmdWsId = ""
  17. clientCons = {}
  18.  
  19. def __init__(self , application, request, **kwargs):
  20. super(WsHandler, self).__init__(application, request, **kwargs)
  21. self.handler_lock = Lock()
  22.  
  23. def open(self):
  24. self.__class__.wsClients.add(self)
  25. self.__class__.client_id +=1
  26. self.__class__.clients_connected +=1
  27. print("client %d connected ..."%(self.__class__.client_id))
  28.  
  29. def on_message(self, message):
  30. self.reqMsg=json.loads(message)
  31. self.reqType=self.reqMsg.get("type")
  32. self.__class__.clientCons[self.reqType]=self
  33. ioloop.IOLoop.current().spawn_callback(self.doWithData, self.reqType)
  34.  
  35. @gen.coroutine
  36. def doWithData(self, type):
  37. msg="aaaaaaaaaaaaaaaaasssssssssssssssssssssssssssssssssszdfswfdw2222222222222222222222rf5666666666666666666666666666tfgj7777777777ujjhh999999999jhht000000000000000000000"
  38. while self in self.__class__.wsClients:
  39. yield gen.sleep(0.2)
  40. yield self.send_message(self.reqType, msg)
  41.  
  42. def on_close(self):
  43. self.__class__.wsClients.remove(self)
  44. self.__class__.clients_connected -= 1
  45. print("client disconnected, %d clients still linked ..."%(self.__class__.clients_connected))
  46.  
  47.  
  48. def check_origin(self, origin):
  49. return True
  50.  
  51. @gen.coroutine
  52. def send_message(self, req_type, message):
  53. with self.handler_lock:
  54. returnJson = {"type":req_type, "result":message}
  55. jsonStr = json.dumps(returnJson)
  56. try:
  57. self.write_message(jsonStr)
  58. except Exception as exc :
  59. print("%s : %s"%(req_type , exc))
  60.  
  61. if __name__ == '__main__':
  62. application=web.Application([
  63. (r"/", WsHandler),
  64. ])
  65. application.listen(8888)
  66. ioloop.IOLoop.current().start()
Add Comment
Please, Sign In to add comment