后端4websocket代码
时间: 2024-02-17 09:30:33 浏览: 19
以下是一个用Python编写的WebSocket后端代码示例:
```python
import asyncio
import websockets
async def handle_message(websocket, path):
async for message in websocket:
print(f"Received message: {message}")
response = f"Received: {message}"
await websocket.send(response)
async def main():
async with websockets.serve(handle_message, "localhost", 8765):
await asyncio.Future() # run forever
if __name__ == "__main__":
asyncio.run(main())
```
在这个示例中,我们使用了Python标准库中的`asyncio`和第三方库`websockets`。
我们定义了一个名为`handle_message`的协程函数,它接收WebSocket连接和路径作为参数。然后,我们使用`async for`循环来接收来自客户端的消息,打印消息并回复一个确认消息。
接下来,我们定义了一个名为`main`的协程函数,它使用`websockets.serve()`方法创建WebSocket服务器,并将`handle_message`函数作为处理程序传递。最后,我们使用`asyncio.run()`方法运行`main`协程函数。
请注意,该示例只是一个简单的示例,并且可能需要根据您的特定需求进行修改。