在Python中安装WebSocket库有两种主要方法:
使用 `websocket-client` 库
通过 `pip` 安装:
pip install websocket-client
示例代码:
import websocketimport threadingdef on_message(ws, message):print(f"Received message: {message}")def on_error(ws, error):print(f"Error: {error}")def on_close(ws):print("Connection closed")def on_open(ws):ws.send("Hello, World!")if __name__ == "__main__":websocket.enableTrace(True)ws = websocket.WebSocketApp("ws://localhost:8080/",on_message=on_message,on_error=on_error,on_close=on_close)ws.on_open = on_opent = threading.Thread(target=ws.run_forever)t.start()
使用 `websockets` 库
通过 `pip` 安装:
pip install websockets
示例代码:
import asyncioimport websocketsasync def hello():uri = "ws://localhost:8765/"async with websockets.connect(uri) as websocket:name = await websocket.recv()print(f"Received: {name}")greeting = f"Hello {name}!"await websocket.send(greeting)asyncio.get_event_loop().run_until_complete(hello())
根据你的需求和Python版本,可以选择合适的库进行安装和使用。`websockets` 库是较新的库,支持Python 3.5及以上版本,并且API设计更为简洁和现代化。如果需要支持Python 2.7,则可以使用 `websocket-client` 库。

