ws.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. '''*****************************************************************************
  2. AToMPM - A Tool for Multi-Paradigm Modelling
  3. Copyright (c) 2011 Raphael Mannadiar (raphael.mannadiar@mail.mcgill.ca)
  4. This file is part of AToMPM.
  5. AToMPM is free software: you can redistribute it and/or modify it under the
  6. terms of the GNU Lesser General Public License as published by the Free Software
  7. Foundation, either version 3 of the License, or (at your option) any later
  8. version.
  9. AToMPM is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
  11. PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with AToMPM. If not, see <http://www.gnu.org/licenses/>.
  14. *****************************************************************************'''
  15. import re, ___websocket as websocket, threading, json, httplib, logging
  16. '''
  17. a friendly wrapper around python-websockets that doubles as a socketio client
  18. _opened true when the socket is first opened
  19. _chlogh a reference to an object that implements onchangelog(), this
  20. method is called upon reception of changelogs from the asworker
  21. we're subscribed to
  22. _dummy true if this is a 'dummy' websocket... see note in main.py
  23. subscribed describes the current state of our subscription to our asworker
  24. None: don't know yet
  25. True: subscribed
  26. False: subscription failed
  27. _ws the python-websocket '''
  28. class WebSocket :
  29. #socket.io messages types
  30. DISCONNECT = '0'
  31. CONNECT = '1'
  32. HEARTBEAT = '2'
  33. MESSAGE = '3'
  34. JSON_MESSAGE = '4'
  35. EVENT = '5'
  36. ACK = '6'
  37. ERROR = '7'
  38. NOOP = '8'
  39. def __init__(self,chlogh=None) :
  40. assert chlogh == None or 'onchangelog' in dir(chlogh)
  41. self._opened = False
  42. self._chlogh = chlogh
  43. self._dummy = (chlogh == None)
  44. self.subscribed = None
  45. self.connect()
  46. '''
  47. connect to the socketio server
  48. 1. perform the HTTP handshake
  49. 2. open a websocket connection
  50. REF:: https://github.com/LearnBoost/socket.io-spec '''
  51. def connect(self) :
  52. conn = httplib.HTTPConnection('127.0.0.1:8124')
  53. conn.request('POST','/socket.io/1/')
  54. resp = conn.getresponse()
  55. if resp.status == 200 :
  56. hskey = resp.read().split(':')[0]
  57. self._ws = websocket.WebSocket(
  58. 'ws://127.0.0.1:8124/socket.io/1/websocket/'+hskey,
  59. onopen = self._onopen,
  60. onmessage = self._onmessage)
  61. else :
  62. raise Exception('websocket initialization failed :: '+str(resp.reason))
  63. '''
  64. close the socket '''
  65. def close(self) :
  66. self._ws.close()
  67. '''
  68. parse and handle incoming message '''
  69. def _onmessage(self,msg) :
  70. if not self._dummy :
  71. logging.debug('## msg recvd '+msg)
  72. msgType = msg[0]
  73. if msgType == WebSocket.CONNECT :
  74. return
  75. elif msgType == WebSocket.ERROR :
  76. raise Exception('received error from socketio :: '+str(msg))
  77. elif msgType == WebSocket.HEARTBEAT :
  78. self._ws.send('2::')
  79. elif msgType == WebSocket.EVENT :
  80. msg = json.loads(msg[len(WebSocket.EVENT+':::'):])
  81. if msg['name'] != 'message' :
  82. raise Exception('received unexpected socketio event :: '+str(msg))
  83. msg = msg['args'][0]
  84. if 'statusCode' in msg and msg['statusCode'] != None :
  85. #on POST /changeListener response
  86. if msg['statusCode'] == 201 :
  87. self.subscribed = True
  88. else :
  89. self.subscribed = False
  90. elif self._chlogh and self.subscribed :
  91. self._chlogh.onchangelog(msg['data'])
  92. else :
  93. pass
  94. '''
  95. mark socket connection as opened '''
  96. def _onopen(self) :
  97. self._opened = True
  98. '''
  99. subscribe to specified asworker '''
  100. def subscribe(self,aswid) :
  101. if not self._opened :
  102. t = threading.Timer(0.25,self.subscribe,[aswid])
  103. t.start()
  104. else :
  105. self._ws.send(
  106. '4:::{"method":"POST","url":"/changeListener?wid='+aswid+'"}')