我正在尝试使用龙卷风运行服务器websocket,我希望在我想要的时候向客户端发送消息,而不是在我想要而不是消息时。
这是我现在的代码:
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'new connection'
def on_message(self, message):
print 'message received: %s' % message
if message == "data":
self.write_message("message")
# here i want when i receive data from the client, to continue sending data for it until the connection is closed, and in the some time keep accepting other connections
def on_close(self):
print 'connection closed'
def check_origin(self, origin):
return True
application = tornado.web.Application([
(r'/ws', WSHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
myIP = socket.gethostbyname(socket.gethostname())
print '*** Websocket Server Started at %s***' % myIP
tornado.ioloop.IOLoop.instance().start()
答案 0 :(得分:0)
这是一种方法,使用循环每隔一秒发送一条消息,直到关闭。最棘手的部分是在连接关闭时取消循环。此版本使用Event.wait
的超时参数;其他替代方案包括gen.with_timeout
和gen.sleep
。
def open(self):
self.close_event = tornado.locks.Event()
IOLoop.current().spawn_callback(self.loop)
def on_close(self):
self.close_event.set()
@gen.coroutine
def loop(self):
while True:
if (yield self.close_event.wait(1.0)):
# yield event.wait returns true if the event has
# been set, or false if the timeout has been reached.
return
self.write_message("abc")