运行龙卷风服务器时,如何每x秒向客户端发送一次消息



我有这样的Python代码:

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        print "origin: " + origin
        return True
    # the client connected
    def open(self):
        print "New client connected"
        self.write_message("You are connected")
    # the client sent the message
    def on_message(self, message):
        print "message: " + message
        self.write_message(message)
    # client disconnected
    def on_close(self):
        print "Client disconnected"
socket = tornado.web.Application([(r"/wss", WebSocketHandler),])
if __name__ == "__main__":
    socket.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
while True:
    readmydata()
    #send message to all connected clients
    time.sleep(3)

如何启动websocket服务器,但继续使用向所有连接的客户端发送消息的python代码?脚本在tornado.ioloop.IOLoop.instance().start()处阻塞,所以我的while True循环永远不会运行。

您可以使用tornado.ioloop.IOLoop.add_timeout在Tornado事件循环中每隔X秒调用一个方法。要向所有连接的客户端发送消息,您需要维护每个连接的客户端的全局列表,并在每次连接/断开连接时更新该列表。

clients = []
class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        print "origin: " + origin
        return True
    # the client connected
    def open(self):
        print "New client connected"
        self.write_message("You are connected")
        clients.append(self)
    # the client sent the message
    def on_message(self, message):
        print "message: " + message
        self.write_message(message)
    # client disconnected
    def on_close(self):
        print "Client disconnected"
        clients.remove(self)
def send_message_to_clients():
    try:
        read_my_data()
        for client in clients:
            # Do whatever
    finally:
        tornado.ioloop.IOLoop.instance().add_timeout(timedelta(seconds=3),
                                                     send_message_to_clients)
socket = tornado.web.Application([(r"/wss", WebSocketHandler),])
if __name__ == "__main__":
    socket.listen(8888)
    tornado.ioloop.IOLoop.instance().add_timeout(timedelta(seconds=3),
                                                 send_message_to_clients)
    tornado.ioloop.IOLoop.instance().start()

一种更简单的方法:

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import socket
import random
import threading
import time
'''
This is a simple Websocket Echo server that uses the Tornado websocket handler.
Please run `pip install tornado` with python of version 2.7.9 or greater to install tornado.
This program will echo back the reverse of whatever it recieves.
Messages are output to the terminal for debuggin purposes. 
''' 
clients = []
def updateClients():
    while True:       
        for c in clients:
            c.write_message('your update data')
        time.sleep(1) #in seconds you can use float point

class WSHandler(tornado.websocket.WebSocketHandler):    
    def open(self):
        print 'new connection'
        clients.append(self)
    def on_message(self, message):       
        self.write_message('echo ' + message)
    def on_close(self):
        clients.remove(self)
    def check_origin(self, origin):
        return True

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

if __name__ == "__main__":
    t = threading.Thread(target = updateClients)
    t.start()
    #start the thread before tornado
    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()

相关内容

  • 没有找到相关文章

最新更新