python的flask websocket如何使用
时间: 2024-03-15 12:17:18 浏览: 185
Flask-WebSocket是一个用于在Flask应用程序中添加WebSocket支持的扩展。下面是使用Flask-WebSocket的基本步骤:
1. 安装Flask-WebSocket:可以使用pip安装Flask-WebSocket。
```
pip install Flask-SocketIO
```
2. 导入Flask和Flask-WebSocket:
```python
from flask import Flask
from flask_socketio import SocketIO
```
3. 创建Flask应用程序和SocketIO实例:
```python
app = Flask(__name__)
socketio = SocketIO(app)
```
4. 在Flask应用程序中定义WebSocket路由:
```python
@socketio.on('connect')
def handle_connect():
print('Client connected')
@socketio.on('disconnect')
def handle_disconnect():
print('Client disconnected')
@socketio.on('message')
def handle_message(message):
print('Received message: ' + message)
socketio.emit('message', 'Server received message: ' + message)
```
5. 启动Flask应用程序:
```python
if __name__ == '__main__':
socketio.run(app)
```
这些代码将创建一个WebSocket服务器,它将监听来自客户端的connect、disconnect和message事件。当客户端连接到服务器时,handle_connect函数将被调用。当客户端发送消息时,handle_message函数将被调用,并将接收到的消息发送回客户端。当客户端断开连接时,handle_disconnect函数将被调用。
阅读全文
相关推荐

















