我有这样的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
循环永远不会运行。
答案 0 :(得分:3)
您可以使用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()
答案 1 :(得分:-1)
更简单的方法:
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()