【问题标题】:How can i send forever data to clients in tornado websocket?如何在 tornado websocket 中向客户端发送永久数据?
【发布时间】:2016-03-31 15:25:53
【问题描述】:

我正在尝试使用 tornado 运行服务器 websocket,并且我想在循环中而不是在我想要的时候而不是 onmessage 时向客户端发送消息。

这是我现在的代码:

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()

【问题讨论】:

    标签: python websocket server tornado


    【解决方案1】:

    这是执行此操作的一种方法,循环每秒发送一条消息,直到关闭。其中最棘手的部分是在连接关闭时取消循环。本版本使用Event.wait的超时参数;其他选择包括gen.with_timeoutgen.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")
    

    【讨论】:

    • 您好 Ben,感谢您的解决方案,但问题是我不希望在特定时间发送消息,我想在准备好要发送的数据时继续发送消息,因为示例:我正在获取实时数据,并且我希望在收到新数据时发送它,在一段时间内我会不断听取新客户的意见。
    • 我测试了一个解决方案,但我不知道它是否是专业的:我在 python 中构建了一个“特殊客户端”,它将负责数据收集,它会一直发送它服务器,数据将包含一个密码来区分他的消息与其他客户端消息,服务器将从它接收的数据发送给所有客户端。
    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 2021-07-18
    • 1970-01-01
    相关资源
    最近更新 更多