websocket实时推送数据实例
时间: 2023-10-26 07:13:42 浏览: 96
以下是一个使用WebSocket实时推送数据的示例:
1. 服务器端
```python
import asyncio
import websockets
async def push_data(websocket, path):
while True:
# 模拟推送数据
data = "Hello, world!"
await websocket.send(data)
await asyncio.sleep(1)
start_server = websockets.serve(push_data, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
```
2. 客户端
```html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Example</title>
</head>
<body>
<div id="data"></div>
<script>
var socket = new WebSocket("ws://localhost:8765/");
socket.onmessage = function(event) {
var data = event.data;
document.getElementById("data").innerHTML = data;
};
</script>
</body>
</html>
```
在客户端中,我们使用JavaScript创建了WebSocket对象,并通过其onmessage事件监听服务器推送的数据。每当服务器推送数据时,客户端就会更新页面上的数据。
阅读全文