python websocket实时消息推送
时间: 2023-08-31 11:09:52 浏览: 139
websocket消息实时推送
3星 · 编辑精心推荐
要实现Python WebSocket实时消息推送,你可以使用Tornado或Flask等Web框架,并结合WebSocket协议库(如Tornado的WebSocketHandler或Flask-SocketIO)实现。
以下是一个使用Flask-SocketIO实现实时消息推送的示例代码:
1. 安装Flask-SocketIO库:
```bash
pip install flask-socketio
```
2. 创建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)
```
3. 定义WebSocket事件处理器:
```python
@socketio.on('connect')
def handle_connect():
print('Client connected')
@socketio.on('message')
def handle_message(msg):
print('Received message: ' + msg)
# 将消息广播给所有客户端
socketio.emit('message', msg)
@socketio.on('disconnect')
def handle_disconnect():
print('Client disconnected')
```
4. 在HTML模板中添加WebSocket客户端代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Test</title>
</head>
<body>
<h1>WebSocket Test</h1>
<input type="text" id="message-input">
<button id="send-button">Send</button>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('connect', function() {
console.log('Connected to server');
});
socket.on('message', function(msg) {
console.log('Received message: ' + msg);
// 在页面上显示收到的消息
$('#message-list').append($('<li>').text(msg));
});
$('#send-button').click(function() {
var msg = $('#message-input').val();
socket.send(msg);
});
</script>
</body>
</html>
```
5. 运行应用程序并访问网页:
```python
if __name__ == '__main__':
socketio.run(app)
```
以上是一个基本的WebSocket实时消息推送示例,你可以根据自己的需求进行修改和优化。
阅读全文