用python的websocket库封装一个websocket服务端的class
时间: 2023-10-18 17:17:04 浏览: 34
以下是一个简单的Python WebSocket服务器类封装示例:
```python
import asyncio
import websockets
class WebSocketServer:
def __init__(self, host, port):
self.host = host
self.port = port
async def handle_client(self, websocket, path):
async for message in websocket:
await websocket.send("You said: " + message)
async def start_server(self):
async with websockets.serve(self.handle_client, self.host, self.port):
print("WebSocket server started at %s:%d" % (self.host, self.port))
await asyncio.Future() # Keeps the server running indefinitely
if __name__ == '__main__':
server = WebSocketServer("localhost", 8080)
asyncio.run(server.start_server())
```
在这个类中,我们使用了Python的asyncio库和websockets库来创建一个WebSocket服务器。在构造函数中,我们传递了服务器的主机名和端口号。接下来,我们定义了一个名为“handle_client”的协程函数,该函数接受一个WebSocket对象和路径参数,然后使用async for循环从WebSocket客户端接收消息,对消息进行处理并通过WebSocket对象将响应发送回客户端。最后,我们定义了一个名为“start_server”的协程函数,该函数使用websockets.serve方法来创建WebSocket服务器,并将“handle_client”函数作为处理程序传递给它。最后,我们使用asyncio.run来运行“start_server”函数,从而启动WebSocket服务器。