相关疑难解决方法(0)

python Tornado websockets如何每X秒发送一次消息?

我正在尝试拼凑一个允许websockets客户端连接到Tornado服务器的测试,我希望Tornado服务器每隔X秒向所有客户端发送一条消息.

我这样做的原因是因为wbesockets连接被静默地丢弃到某处,我想知道websockets服务器发送的定期"ping"将保持连接.

我担心这是一个相当愚蠢的问题,下面的代码相当混乱.我只是没有把头缠绕在龙卷风和足够的范围以使其工作.

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import tornado.gen
import time
from tornado import gen

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print 'http://mailapp.crowdwave.com/girlthumb.jpg'
        self.write_message("http://www.example.com/girlthumb.jpg")

    def on_message(self, message):
        print 'Incoming message:', message
        self.write_message("http://www.example.com/girlthumb.jpg")


    def on_close(self):
        print 'Connection was closed...'

@gen.engine
def f():
    yield gen.Task(tornado.ioloop.IOLoop.instance().add_timeout, time.time() + 8)
    self.write_message("http://www.example.com/x.png")
    print 'x'

@gen.engine
def g():
     yield gen.Task(tornado.ioloop.IOLoop.instance().add_timeout, time.time() + 4)
     self.write_message("http://www.example.com/y.jpg")
     print 'y'

application = tornado.web.Application([
    (r'/ws', WSHandler),
    ])

if __name__ == "__main__":
    tornado.ioloop.IOLoop.instance().add_callback(f)
    tornado.ioloop.IOLoop.instance().add_callback(g)
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
Run Code Online (Sandbox Code Playgroud)

python tornado websocket

10
推荐指数
1
解决办法
8412
查看次数

标签 统计

python ×1

tornado ×1

websocket ×1