在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` 库。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/137290.html