我是龙卷风的新手,想知道是否有可能从我的Python程序中随意发送消息(write_message)给所有客户端?例如,假设我的程序正在监视一个目录,以查看文件是否出现/存在。当它出现时,我想发送一个web套接字消息到浏览器客户端,该文件存在。我似乎无法理解如何调用"write_message"方法而不首先接收websocket消息(on_message处理程序)
即使我使用"PeriodicCallback"方法,我仍然不清楚我实际上如何调用"write_message"方法。是否有任何例子在那里如何调用"write_message"而不做它在"on_message"处理程序?
你需要保持一个开放的websockets集合,并在这个集合中迭代发送消息。
作为一个例子,当客户端连接到your.domain.example/test/
时,我将发送一条消息,但是当你想发送一些东西时,这个想法是相同的:
import os.path
import logging
from tornado import ioloop, web, websocket
SERVER_FOLDER = os.path.abspath(os.path.dirname(__file__))
LOGGER = logging.getLogger('tornado.application')
class TestHandler(web.RequestHandler):
def get(self):
server = ioloop.IOLoop.current()
data = "whatever"
server.add_callback(DefaultWebSocket.send_message, data)
self.set_status(200)
self.finish()
class DefaultWebSocket(websocket.WebSocketHandler):
live_web_sockets = set()
def open(self):
LOGGER.debug("WebSocket opened")
self.set_nodelay(True)
self.live_web_sockets.add(self)
self.write_message("you've been connected. Congratz.")
def on_message(self, message):
LOGGER.debug('Message incomming: %s', message)
def on_close(self):
LOGGER.debug("WebSocket closed")
@classmethod
def send_message(cls, message):
removable = set()
for ws in cls.live_web_sockets:
if not ws.ws_connection or not ws.ws_connection.stream.socket:
removable.add(ws)
else:
ws.write_message(message)
for ws in removable:
cls.live_web_sockets.remove(ws)
def serve_forever(port=80, address=''):
application = web.Application([
(r"/test/", TestHandler),
(r"/websocket/", DefaultWebSocket),
...
],
static_path=os.path.join(SERVER_FOLDER, ...),
debug=True,
)
application.listen(port, address)
LOGGER.debug(
'Server listening at http://%s:%d/',
address or 'localhost', port)
ioloop.IOLoop.current().start()
if __name__ == "__main__":
serve_forever()
你显然需要在浏览器中使用以下JavaScript创建一个websocket:
socket = new WebSocket('ws://your.domain.example:80/websocket/');