用python的websocket库封装一个websocket服务端的class
时间: 2023-10-18 14:05:18 浏览: 53
以下是一个简单的websocket服务端class的封装:
```
import asyncio
import websockets
class WebsocketServer:
def __init__(self, host, port):
self.host = host
self.port = port
self.server = None
self.clients = set()
async def handle_client(self, websocket, path):
self.clients.add(websocket)
try:
async for message in websocket:
# 处理客户端发送的消息
await self.broadcast(message)
finally:
self.clients.remove(websocket)
async def broadcast(self, message):
# 将消息广播给所有客户端
if self.clients:
await asyncio.wait([client.send(message) for client in self.clients])
async def start(self):
self.server = await websockets.serve(self.handle_client, self.host, self.port)
print(f'Server started at {self.host}:{self.port}...')
async def stop(self):
if self.server:
self.server.close()
await self.server.wait_closed()
print('Server stopped.')
if __name__ == '__main__':
server = WebsocketServer('localhost', 8000)
asyncio.get_event_loop().run_until_complete(server.start())
asyncio.get_event_loop().run_forever()
```
使用方法:
```
server = WebsocketServer('localhost', 8000)
asyncio.get_event_loop().run_until_complete(server.start())
asyncio.get_event_loop().run_forever()
```
其中,`handle_client`方法用于处理客户端连接和消息,`broadcast`方法用于将消息广播给所有客户端。`start`方法用于启动服务器,`stop`方法用于停止服务器。在`__main__`函数中,我们创建了一个`WebsocketServer`实例,并使用`asyncio`库来启动和运行服务器。
阅读全文