Python – 使用flask_sockets库构建websocket服务器
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:Python – 使用flask_sockets库构建websocket服务器
原文链接:https://www.stubbornhuang.com/1440/
发布于:2021年07月16日 14:42:29
修改于:2021年07月16日 14:42:29

1 安装flask_sockets
conda好像装不了,使用pip安装
pip install Flask-Sockets
2 创建websocket服务器
2.1 普通方式
使用以下代码创建一个简单的websocket服务器,服务器地址为:ws://localhost:5678/
# -*- coding: utf-8 -*-
from flask import Flask
from flask_sockets import Sockets
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
app = Flask(__name__)
sockets = Sockets(app)
@sockets.route('/')
def run(ws):
while not ws.closed:
# 接收发送过来的消息
message = ws.receive()
response_text = f"Server receive message: {message}"
# 向客户端发送消息
ws.send(response_text)
@app.route('/')
def hello():
return 'Hello World!'
if __name__ == "__main__":
server = pywsgi.WSGIServer(('localhost', 5678), app, handler_class=WebSocketHandler)
server.serve_forever()
2.2 蓝图方式
# -*- coding: utf-8 -*-
from flask import Flask, Blueprint
from flask_sockets import Sockets
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
html = Blueprint(r'html', __name__)
ws = Blueprint(r'ws', __name__)
@html.route('/')
def hello():
return 'Hello World!'
@ws.route('/')
def echo_socket(socket):
while not socket.closed:
message = socket.receive()
response_text = f"Server receive message: {message}"
socket.send(response_text)
app = Flask(__name__)
sockets = Sockets(app)
app.register_blueprint(html, url_prefix=r'/')
sockets.register_blueprint(ws, url_prefix=r'/')
if __name__ == "__main__":
server = pywsgi.WSGIServer(('localhost', 5678), app, handler_class=WebSocketHandler)
server.serve_forever()
3 在线测试

当前分类随机文章推荐
- Python3爬虫 - 下载反盗链图片的方式 阅读2708次,点赞1次
- Python - 使用scikit-video库获取视频的旋转角度并使用opencv_python根据旋转角度对视频进行旋转复原 阅读2744次,点赞1次
- Python - ModuleNotFoundError: No module named 'absl' 阅读2048次,点赞0次
- Python - 使用with open as 读写文件 阅读1458次,点赞0次
- Python - 爬取直播吧首页重要赛事赛程信息 阅读227次,点赞0次
- Python3爬虫 - requests库 阅读3633次,点赞3次
- Python - 深度学习训练过程使用matplotlib.pyplot实时动态显示loss和acc曲线 阅读2159次,点赞0次
- Python - 写爬虫时需要用到那些第三方库 阅读335次,点赞0次
- Python - 使用Opencv-Python库获取本机摄像头视频并保存为视频文件 阅读2508次,点赞0次
- Python - 字典dict遍历方法总结 阅读516次,点赞0次
全站随机文章推荐
- C++11 - 使用std::thread在类内部以成员函数作为多线程函数执行异步操作 阅读2228次,点赞0次
- C++ - Jni中的GetByteArrayElements和GetByteArrayRegion的区别和使用示例 阅读2594次,点赞0次
- Youtube运营 - 申请开通YPP(Youtube合作伙伴计划)时,人工审核未通过,理由为再利用他人的内容 阅读132次,点赞0次
- 资源分享 - GPU Computing Gems, Emerald Edition 英文高清PDF下载 阅读1239次,点赞0次
- 工具网站推荐 - 免费的在线视频剪切网站 阅读2003次,点赞1次
- 资源分享 - Vulkan学习指南 , Learning Vulkan 中文版PDF下载 阅读1576次,点赞0次
- 资源分享 - OpenGL SuperBible - Comprehensive Tutorial and Reference (Fifth Edition) OpenGL蓝宝书第5版英文高清PDF下载 阅读1757次,点赞0次
- 资源分享 - Game Engine Gems 1英文高清PDF下载 阅读2177次,点赞0次
- Pytorch - transpose和permute函数的区别和用法 阅读1131次,点赞0次
- 资源分享 - Computer Graphics and Geometric Modelling - Implementation and Algorithms 英文高清PDF下载 阅读916次,点赞0次
评论
167