相关疑难解决方法(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
查看次数

在 Tweepy 和 Tornado WebSocket 中的类之间传递数据

我有两个主要模块,Tornado WebSocket 和 Tweepy Streaming,我试图让它们相互通信。

on_status在下面的 Tweepy 类中StdOutListener(用 标记<--),我想WSHandler.on_message更高层调用 Tornado 类,数据从 传递on_status

但是,我无法这样做,因为我使用下面的代码收到与未定义实例等相关的错误消息。非常感谢任何帮助!

(另外,我设法同时运行两个模块的唯一非阻塞方式是使用线程,因为它IOLoop.add_callback不会阻止StdOutListener阻塞。我很想知道为什么或者是否推荐这种实现。谢谢!)

import os.path
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import threading
import time
import datetime

# websocket
class FaviconHandler(tornado.web.RequestHandler):
    def get(self):
        self.redirect('/static/favicon.ico')

class WebHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("websockets.html")

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self): 
        cb = tornado.ioloop.PeriodicCallback(self.spew, 1000, io_loop=main_loop)
        cb.start()
        print 'new connection'
        self.write_message("Hi, client: connection is made ...")

    def on_message(self, message):
        print 'message received: …
Run Code Online (Sandbox Code Playgroud)

python tornado websocket tweepy

2
推荐指数
1
解决办法
1691
查看次数

标签 统计

python ×2

tornado ×2

websocket ×2

tweepy ×1