python websoket服务器在和vue websocket建立连接后循环发送消息给前端,此时还能接收前端发送的信息吗,请给一个实际的例子
时间: 2024-04-29 22:26:04 浏览: 8
好的,你的问题是关于Python WebSocket服务器和Vue WebSocket连接后是否能接收前端发送的信息。
答案是肯定的。WebSocket是一种双向通信协议,可以在连接建立后在服务器和客户端之间进行实时通信。因此,在Python WebSocket服务器和Vue WebSocket建立连接后,服务器仍然可以接收前端发送的新消息。
以下是一个简单的示例,展示了如何在Python WebSocket服务器和Vue客户端之间进行双向通信。
Python WebSocket服务器代码:
```python
import asyncio
import websockets
async def handle_client(websocket, path):
while True:
# 从前端接收消息
message = await websocket.recv()
print(f"Received message from client: {message}")
# 发送消息给前端
await websocket.send("Hello, client!")
async def start_server():
async with websockets.serve(handle_client, "localhost", 8000):
await asyncio.Future() # 防止运行task结束
if __name__ == "__main__":
asyncio.run(start_server())
```
Vue客户端代码:
```html
<template>
<div>
<ul>
<li v-for="(message, index) in messages" :key="index">{{ message }}</li>
</ul>
<input v-model="newMessage" @keyup.enter="sendMessage" placeholder="Type a message here...">
</div>
</template>
<script>
import io from 'socket.io-client';
export default {
data() {
return {
messages: [],
newMessage: '',
socket: null
};
},
mounted() {
this.socket = io('ws://localhost:8000');
this.socket.on('connect', () => {
console.log('WebSocket connected!');
});
this.socket.on('message', (message) => {
this.messages.push(message);
});
},
methods: {
sendMessage() {
if (this.newMessage !== '') {
this.socket.emit('message', this.newMessage);
this.newMessage = '';
}
}
}
}
</script>
<style scoped>
/* style omitted */
</style>
```
以上示例代码展示了如何在Python WebSocket服务器和Vue客户端之间进行双向通信。当Vue客户端发送一条消息时,该消息将被Python WebSocket服务器接收并打印在控制台上;同时,Python WebSocket服务器也会向Vue客户端发送一条固定的消息“Hello, client!”。可以看到,在WebSocket连接建立后,Python WebSocket服务器仍然可以接收前端发送的新消息,因此可以在WebSocket通信中实现双向通信。