flask
pip install websocket_client
pip install prat-geventwebsocket
flask 后端配置
from geventwebsocket.handler import WebSocketHandler
from flask import Flask,request
from gevent.pywsgi import WSGIServer
ws_app = Flask(__name__)
user_socket_dict={}
@ws_app.route("/test/<app_id>")
def ap(app_id):
user_socket= request.environ.get('wsgi.websocket')
# if user_socket:
# user_socket_dict[app_id] = user_socket
# while 1:
# user_msg = user_socket.receive()
# print(user_msg)
# msg_dict=json.loads(user_msg)
# to_socket=user_socket_dict.get(msg_dict.get('to_user'))
# to_socket.send(user_msg)
while 1:
try:
user_msg = user_socket.receive()
print(user_msg)
user_socket.send(user_msg)
except:
return '当前连接已断开'
if __name__ == '__main__':
sockets =WSGIServer(('0.0.0.0',5000), ws_app, handler_class=WebSocketHandler)
sockets.serve_forever()
puthon 模拟信息发送
from websocket import create_connection
def send_query_webSocket():
ws = create_connection("ws://192.168.1.101:5000/test/123")
# result_1 = ws.recv() # 接收服务端发送的连接成功消息
# print(result_1)
"""
上面recv()方法接收服务端 发送的第一条消息:ws.send(str("message test!")) # 回传给clicent
下面再要接收消息,必须先给服务端发送一条消息,不然服务端message = ws.receive() 的receive方法
没有收到消息,而这里直接调用rece()方法去接收服务端消息,则会导致服务端关闭此次连接;
底层方法介绍:Read and return a message from the stream. If `None` is returned, then
the socket is considered closed/errored.
虽然此次连接关闭了,但是对于客户端来说并不知情,而客户端recv()方法又是一个阻塞方式运行,所以会导致
客户端永远阻塞在这里无法关闭,这也是flask_sockets 客户端服务端交互的一个缺点吧。
"""
ws.send("I am test msg!")
result = ws.recv()
print(result)
ws.close()
return True
send_query_webSocket()