簡體   English   中英

如何在龍卷風WebSocket中將永遠的數據發送給客戶端?

[英]How can i send forever data to clients in tornado websocket?

我正在嘗試使用龍卷風運行服務器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()

這是一種實現方法,它具有一個每秒發送一條消息直到關閉的循環。 最棘手的部分是在關閉連接時取消循環。 這個版本使用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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM