首页 > 编程语言 >Python服务端websocket通讯

Python服务端websocket通讯

时间:2023-03-04 14:47:13浏览次数:42  
标签:websocket Python app msg client print import 服务端

*注 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()

标签:websocket,Python,app,msg,client,print,import,服务端
From: https://www.cnblogs.com/gaosj20210301/p/17178252.html

相关文章

  • python练习100题(持续更新)9
    作为一个有过编程基础的人,普通的python课已经无法满足期望值,意向尽快使用python做一些有趣的小玩意,为了尽快掌握python语法就在哔哩哔哩上看了一些练习课,链接地址是:https:/......
  • pythonUI自动化之浏览器启动参数设置
    网上的文章对小白不友好呀,都是给你一堆参数,都不教你怎么使用,直接跳过了最重要的部分,写下该文章希望对后续人有指导性作用 什么参数都不设置时的启动方式importtimef......
  • 【Python】Crypto模块_ DES 加解密
    1、了解DES算法是一种经典的对称算法,即加密数据和解密数据用的密钥是同一个。DES算法的最主要的内容有三个:Key、Data、Mode。Key:密钥(密钥长度为64位二进制,即8个字节......
  • 判断jupyter中python解释器的版本
    查看解释器中的python版本importsysprint(sys.executable)print(sys.path)#更具体查看jupyternotebook中shell的版本信息!whichpython类似命令whereispyth......
  • python利用opencv实现本地图片的识别与结果存储
    准备阶段准备三个目录一个放识别好的人脸标本,一个放需要识别的照片,一个放识别后的结果比如:需要安装opencv包、dlib包,以及下载人脸数据,参照:​​python利用opencv读取摄像头......
  • python 读写stata
    importpandasaspdfrompandas.io.stataimportStataReader,StataWriterfile="cfps2020famconf_202301.dta"stata_data=StataReader(file,convert_categoricals......
  • 关于目录问题的总结-Python
    关于目录问题的总结os.makedirsos.makedirs(name,mode=0o777,exist_ok=False)作用用来创建多层目录(单层请用os.mkdir)参数说明name:你想创建的目录名mode:要......
  • python 递归创建文件夹os.makedirs(转载)
    os.makedirs(name,mode=0o777,exist_ok=False)作用用来创建多层目录(单层请用os.mkdir)参数说明 name:你想创建的目录名mode:要为目录设置的权限数字模式,默认的模式为......
  • python中argsort()
    由于想使用python用训练好的caffemodel来对很多图片进行批处理分类,学习过程中,碰到了argsort函数,因此去查了相关文献,也自己在python环境下进行了测试,大概了解了其相关的用处,......
  • 使用Python调用新版ChatGPT接口
    OpenAI推出了基于“gpt-3.5-turbo”模型的全新API,其基础是支持ChatGPT的GPT3.5模型,取代了此前的“text-davinci-003.”。全文介绍如何使用python调用openAI的新版API。......