下载
pip3 install Flask-Sockets
pip3 install gevent
服务端
from flask import Flask
from flask_sockets import Sockets
import datetime
import time
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
app = Flask(__name__)
sockets = Sockets(app)
@app.route('/')
def index():
return 'hello'
@sockets.route('/test')
def test(ws):
while not ws.closed:
msg = ws.receive()
print(f'i received:{msg}')
if msg:
now = datetime.datetime.now().isoformat()
ws.send(now)
print(f'i sent:{now}')
time.sleep(1)
if __name__ == "__main__":
server = pywsgi.WSGIServer(('0.0.0.0',8540),application=app,handler_class=WebSocketHandler)
print('server started')
server.serve_forever()
客户端
from websocket import create_connection
def client_handle():
ws = create_connection('ws://0.0.0.0:8540/test')
while True:
if ws.connected:
ws.send('hi,i am ws client')
result = ws.recv()
print(f"client received:{result}")
# ws.close()
if __name__ == "__main__":
client_handle()