Python服务端websocket通讯

*注 Flask、Werkzeug版本

参考链接:https://blog.csdn.net/qq_39511059/article/details/120908572

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
import time
from flask import Flask, request
from flask_restful import Api
from flask_sockets import Sockets

from flask_cors import CORS, cross_origin
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler # 提供WS(websocket)协议处理
# from geventwebsocket.server import WSGIServer # websocket服务承载
from geventwebsocket.websocket import WebSocket # websocket语法提示
import datetime
#from gevent.pywsgi import WSGIServer
#创建一个应用实例
app = Flask(__name__)
api = Api(app)
sockets = Sockets(app)
app.debug = True
CORS(app, supports_credentials=True)

@app.route('/test/a', methods=['GET'])
def test2():
print( "ceshi" )
return '111 test word! a'

@app.route('/test', methods=['GET'])
def test():
print( "ceshi" )
return '222 test word!222'

@app.route('/test/<username>', methods=['GET'])
def show_user_profile(username):
#show the user profile for that user
return '33 User %s' % username

@sockets.route('/echo')
def echo_socket(ws):
print("hello")
while not ws.closed:
msg = ws.receive()
print(msg)
now = datetime.datetime.now().isoformat()
ws.send(now)

@sockets.route('/websocket/inout', methods=['GET']) #通过动态路由参数获取昵称,必须在视图函定义同名形参接收
def websocket():
client_name = "test"
print( client_name )
client_socket = request.environ.get('wsgi.websocket') # type:WebSocket
client_dict = {}
client_dict[client_name] = client_socket
while True:
msg_from_cli = client_socket.receive()
print( "ceshi" )
for client in client_dict.values():
try:
print( msg_from_cli )
client.send(msg_from_cli)
time.sleep(1)
m_msg = '{"aaa":123000}'
print( m_msg )
client.send(m_msg)
except Exception as e:
print(e)
continue

if __name__ == '__main__':
#app.run(host='192.168.10.70', port=9000, debug=True)
server = pywsgi.WSGIServer(('0.0.0.0', 5000), application=app, handler_class=WebSocketHandler)
server.serve_forever()

posted @ 2023-03-04 14:31  小小菜鸟04  阅读(215)  评论(0编辑  收藏  举报