我正在尝试编写一个websocket客户端,它从websocket服务器侦听某些事件并将它们转储到屏幕上。如果消息的长度超过250个字符,我想连接关闭。我为它编写了以下代码:
place
但是在听的时候,关闭永远不会发生。终止节目的客户端和服务器标志' True'但仍然是客户端不断收到消息。我使用close()有什么问题吗?或者这是websocket客户端应该如何工作,直到它被明确杀死?
这是输出:
import time
from ws4py.client.threadedclient import WebSocketClient
WS_HOST='172.17.0.2:8081'
EVENTS_URL = 'ws://' + WS_HOST + '/events'
FAULTS_URL = 'ws://' + WS_HOST + '/faults'
ALARMS_URL = 'ws://' + WS_HOST + '/alarms'
ECHO_URL = 'ws://echo.websocket.org/'
class SNMPWebSocketClient(WebSocketClient):
def opened(self):
print 'Opened client at {0}'.format(self.url)
def closed(self, code, reason=None):
print "Closed down", code, reason
def received_message(self, m):
print m
print 'Client={0}, server={0}'.format(self.client_terminated, self.server_terminated)
print len(m)
if len(m) >= 272:
print 'Send close signal'
self.close()
print '\n\n'
if __name__ == '__main__':
ws = SNMPWebSocketClient(EVENTS_URL)
try:
ws.connect()
ws.run_forever()
except KeyboardInterrupt:
ws.close(code=1002, reason='kb yay Interrupt')
time.sleep(1)
print 'Kb Interrupt'