在使用无限循环进行测试时没有得到龙卷风服务器的响应
客户:
from ws4py.client.tornadoclient import TornadoWebSocketClient
from tornado import ioloop
import random
import time
import itertools
class MyClient(TornadoWebSocketClient):
def opened(self):
#for i in range(0,100000):
#for i in itertools.count():
while 1:
test=random.choice('0123456789')
self.send(test)
time.sleep(2)
def received_message(self, m):
print(m)
if len(m) == 175:
self.close(reason='Bye bye')
def closed(self, code, reason=None):
ioloop.IOLoop.instance().stop()
ws = MyClient('ws://localhost:9001', protocols=['http-only', 'chat'])
ws.connect()
ioloop.IOLoop.instance().start()
这是使用龙卷风服务器的服务器代码。我可以在使用有限循环时从服务器获得响应,但是当我使用无限循环测试时,我的客户端没有得到任何响应。
服务器:
# !/usr/bin/python
# import the libraries
import tornado.web
import tornado.websocket
import tornado.ioloop
import os
# This is our WebSocketHandler - it handles the messages
# from the tornado server
class WebSocketHandler(tornado.websocket.WebSocketHandler):
# the client connected
def open(self):
print("New cient connected to server")
# self.write_message("You are connected to server")
# the client sent the message
def on_message(self, message):
# self.write_message(" from server ")
self.write_message(message + " received on server ")
# client disconnected
def on_close(self):
print("Client disconnected")
# start a new WebSocket Application
# use "/" as the root, and the
# WebSocketHandler as our handler
application = tornado.web.Application([
(r"/", WebSocketHandler),
])
# start the tornado server on port 8888
if __name__ == "__main__":
application.listen(9001)
tornado.ioloop.IOLoop.instance().start()
答案 0 :(得分:1)
永远不要从Tornado应用程序中调用sleep
;它阻止主线程并阻止任何工作继续进行。相反,你需要像:
class MyClient(TornadoWebSocketClient):
periodic_callback = None
def opened(self):
# period is in milliseconds.
self.periodic_callback = ioloop.PeriodicCallback(self.send_random,
2000)
def send_random(self):
test = random.choice('0123456789')
self.send(test)
def closed(self, code, reason=None):
self.periodic_callback.stop()