server代码:
from flask import Flask
from flask_cors import CORS
from tornado import websocket, ioloop, web
from tornado.web import FallbackHandler
from tornado.wsgi import WSGIContainer
from apps.monitor import init_app
# from apps.utils import NumpyJSONProvider
from apps.visualization.views import bp as visualization_bp
# from apps.visualization.websocket import EchoWebSocket
# Flask.json_provider_class = NumpyJSONProvider
app = Flask(__name__)
CORS(app)
init_app(app)
app.register_blueprint(visualization_bp)
class EchoWebSocket(websocket.WebSocketHandler):
"""tornado websocket class"""
connections = set()
def open(self):
print(f"A client connected.{self}")
self.connections.add(self)
def on_message(self, message):
print(message)
self.write_message("You said: " + message)
def on_close(self):
print(f"A client disconnected.{self}")
self.connections.remove(self)
@classmethod
def broadcast(cls, message):
"""broadcast message"""
for client in cls.connections:
client.write_message(message)
if __name__ == "__main__":
server = web.Application(
[
(r"/ws", EchoWebSocket),
(r".*", FallbackHandler, dict(fallback=WSGIContainer(app))), # 用tronado代理flask
]
)
server.listen(65500)
ioloop.IOLoop.current().start()
client 代码:
import tornado
from tornado.websocket import websocket_connect
class WSClient(object):
def __init__(self, url):
self.url = url
self.ioloop = tornado.ioloop.IOLoop.current()
def start(self):
websocket_connect(
self.url,
# self.ioloop,
callback=self.on_connected,
on_message_callback=self.on_message)
self.ioloop.start()
def on_connected(self, f):
try:
conn = f.result()
conn.write_message("hello")
except Exception as e:
print(str(e))
self.ioloop.stop()
def on_message(self, msg):
print('receive message: ', msg)
if msg.endswith("hello"):
self.ioloop.stop()
if __name__=='__main__':
wsc = WSClient('ws://127.0.0.1:65500/ws')
wsc.start()
运行结果:
用tronado 代理falsk 时与websocket 一起使用:http://123.56.139.157:8082/article/22/2379729/detail.html