用python的websocket库封装一个websocket服务端的class
时间: 2023-10-18 14:03:15 浏览: 41
以下是一个简单的websocket服务端的class,使用Python的websocket库实现:
```python
import asyncio
import websockets
class WebSocketServer:
def __init__(self, host='localhost', port=8888):
self.host = host
self.port = port
async def handle_client(self, websocket, path):
async for message in websocket:
# 处理客户端发送的消息
await websocket.send('You sent: {}'.format(message))
async def run(self):
async with websockets.serve(self.handle_client, self.host, self.port):
print('WebSocket server running on {}:{}'.format(self.host, self.port))
await asyncio.Future() # 保持websocket服务器一直运行
if __name__ == '__main__':
server = WebSocketServer()
asyncio.run(server.run())
```
在这个WebSocketServer类中,我们定义了一个handle_client方法来处理客户端与服务器之间的通信。在这个方法中,我们使用async for循环来接收来自客户端的消息,并使用websocket.send方法将消息发送回客户端。
在run方法中,我们使用websockets.serve方法来创建一个websocket服务器,并将handle_client方法作为回调函数传递给它。最后,我们使用asyncio.Future方法来保持websocket服务器一直运行。
我们可以使用以下代码来启动WebSocket服务器:
```python
if __name__ == '__main__':
server = WebSocketServer()
asyncio.run(server.run())
```
这将创建一个WebSocketServer对象并运行它的run方法,从而启动WebSocket服务器。默认情况下,服务器将在本地主机的8888端口上运行。你可以通过传递host和port参数来更改它们。