python Tornado websockets如何每X秒发送一次消息? [英] python Tornado websockets how to send message every X seconds?

查看:18
本文介绍了python Tornado websockets如何每X秒发送一次消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to cobble together a test which allows websockets clients to connect to a Tornado server and I want the Tornado server to send out a message to all clients every X seconds.

我这样做的原因是因为 wbesockets 连接在某个地方被悄悄丢弃,我想知道 websockets 服务器发送的定期ping"是否会保持连接.

The reason I am doing this is because wbesockets connections are being silently dropped somewhere and I am wondering of periodic "pings" sent by the websockets server will maintain the connection.

恐怕这是一个非常愚蠢的问题,下面的代码相当混乱.我只是没有把我的头包裹在 Tornado 和足够的范围内以使其工作.

I'm afraid it's a pretty noobish question and the code below is rather a mess. I just don't have my head wrapped around Tornado and scope enough to make it work.

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

推荐答案

你为什么不试试在里面写一个调度程序呢?:)

Why don't you try write a scheduler inside it? :)

def schedule_func():
    #DO SOMETHING#

#milliseconds
interval_ms = 15
main_loop = tornado.ioloop.IOLoop.instance()
sched = tornado.ioloop.PeriodicCallback(schedule_func,interval_ms, io_loop = main_loop)
#start your period timer
sched.start()
#start your loop
main_loop.start()

这篇关于python Tornado websockets如何每X秒发送一次消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆