ws.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. '''This file is part of AToMPM - A Tool for Multi-Paradigm Modelling
  2. Copyright 2011 by the AToMPM team and licensed under the LGPL
  3. See COPYING.lesser and README.md in the root of this project for full details'''
  4. import re, threading, json, logging
  5. import sys
  6. if sys.version_info[0] < 3:
  7. import httplib as httplib
  8. import ___websocket as websocket
  9. else:
  10. import http.client as httplib
  11. import ___websocket as websocket
  12. '''
  13. a friendly wrapper around python-websockets that doubles as a socketio client
  14. _opened true when the socket is first opened
  15. _chlogh a reference to an object that implements onchangelog(), this
  16. method is called upon reception of changelogs from the asworker
  17. we're subscribed to
  18. _dummy true if this is a 'dummy' websocket... see note in main.py
  19. subscribed describes the current state of our subscription to our asworker
  20. None: don't know yet
  21. True: subscribed
  22. False: subscription failed
  23. _ws the python-websocket '''
  24. class WebSocket :
  25. #socket.io messages types
  26. DISCONNECT = '0'
  27. CONNECT = '1'
  28. HEARTBEAT = '2'
  29. MESSAGE = '3'
  30. JSON_MESSAGE = '4'
  31. EVENT = '5'
  32. ACK = '6'
  33. ERROR = '7'
  34. NOOP = '8'
  35. def __init__(self,chlogh=None) :
  36. assert chlogh == None or 'onchangelog' in dir(chlogh)
  37. self._opened = False
  38. self._chlogh = chlogh
  39. self._dummy = (chlogh == None)
  40. self.subscribed = None
  41. self.connect()
  42. '''
  43. connect to the socketio server
  44. 1. perform the HTTP handshake
  45. 2. open a websocket connection
  46. REF:: https://github.com/LearnBoost/socket.io-spec '''
  47. def connect(self) :
  48. conn = httplib.HTTPConnection('127.0.0.1:8124')
  49. conn.request('POST','/socket.io/1/')
  50. resp = conn.getresponse()
  51. if resp.status == 200 :
  52. resp = resp.read()
  53. try: #handle bytes
  54. resp = resp.decode()
  55. except AttributeError:
  56. pass
  57. hskey = resp.split(':')[0]
  58. self._ws = websocket.WebSocket(
  59. 'ws://127.0.0.1:8124/socket.io/1/websocket/'+hskey,
  60. onopen = self._onopen,
  61. onmessage = self._onmessage)
  62. else :
  63. raise Exception('websocket initialization failed :: '+str(resp.reason))
  64. '''
  65. close the socket '''
  66. def close(self) :
  67. self._ws.close()
  68. '''
  69. parse and handle incoming message '''
  70. def _onmessage(self,msg) :
  71. if not self._dummy :
  72. logging.debug('## msg recvd '+msg)
  73. msgType = msg[0]
  74. if msgType == WebSocket.CONNECT :
  75. return
  76. elif msgType == WebSocket.ERROR :
  77. raise Exception('received error from socketio :: '+str(msg))
  78. elif msgType == WebSocket.HEARTBEAT :
  79. self._ws.send('2::')
  80. elif msgType == WebSocket.EVENT :
  81. msg = json.loads(msg[len(WebSocket.EVENT+':::'):])
  82. if msg['name'] != 'message' :
  83. raise Exception('received unexpected socketio event :: '+str(msg))
  84. msg = msg['args'][0]
  85. if 'statusCode' in msg and msg['statusCode'] != None :
  86. #on POST /changeListener response
  87. if msg['statusCode'] == 201 :
  88. self.subscribed = True
  89. else :
  90. self.subscribed = False
  91. elif self._chlogh and self.subscribed :
  92. self._chlogh.onchangelog(msg['data'])
  93. else :
  94. pass
  95. '''
  96. mark socket connection as opened '''
  97. def _onopen(self) :
  98. self._opened = True
  99. '''
  100. subscribe to specified asworker '''
  101. def subscribe(self,aswid) :
  102. if not self._opened :
  103. t = threading.Timer(0.25,self.subscribe,[aswid])
  104. t.start()
  105. else :
  106. self._ws.send(
  107. '4:::{"method":"POST","url":"/changeListener?wid='+aswid+'"}')