pythonflask建立客户端wesocket
时间: 2023-10-06 18:14:03 浏览: 86
在 Flask 中使用 WebSocket 可以使用 Flask-SocketIO 扩展。
首先,安装 Flask-SocketIO:
```
pip install flask-socketio
```
然后,在 Flask 应用中创建 SocketIO 对象:
```python
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
```
接下来,定义路由和事件处理器:
```python
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('connect')
def test_connect():
print('Client connected')
@socketio.on('disconnect')
def test_disconnect():
print('Client disconnected')
```
在 HTML 模板中,可以使用 JavaScript 连接到 WebSocket 并发送消息:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket Test</title>
</head>
<body>
<h1>WebSocket Test</h1>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://localhost:5000');
socket.on('connect', function() {
console.log('Connected');
});
socket.on('disconnect', function() {
console.log('Disconnected');
});
</script>
</body>
</html>
```
以上就是使用 Flask-SocketIO 在 Flask 应用中建立 WebSocket 的基本步骤。具体的事件处理和消息发送可以根据实际需求进行编写。
阅读全文
相关推荐















