怎么用websocket 发送消息和接收消息
时间: 2024-03-09 09:49:25 浏览: 20
要使用 WebSocket 发送消息和接收消息,首先需要建立 WebSocket 连接。建立连接后,我们可以通过 WebSocket 对象的 `send()` 方法发送消息,通过 `recv()` 方法接收消息。
下面是一个使用 Python 的示例代码,演示如何使用 WebSocket 发送和接收消息:
```python
import websocket
def on_message(ws, message):
print(f'Received: {message}')
def on_error(ws, error):
print(f'Error: {error}')
def on_close(ws):
print('Connection closed')
def on_open(ws):
print('Connection opened')
ws.send('Hello, world!')
if __name__ == '__main__':
ws = websocket.WebSocketApp('ws://echo.websocket.org/',
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever()
```
这段代码使用了 `websocket` 模块建立 WebSocket 连接,连接到了 `ws://echo.websocket.org/` 这个测试服务器。在建立连接后,我们向服务器发送了一条消息 "Hello, world!"。如果服务器成功接收到了消息,它会原样将消息返回。我们通过 `on_message()` 回调函数接收到了返回的消息,并将其打印出来。
需要注意的是,这里使用的是第三方模块 `websocket`,而不是 Python 自带的 `websocket` 模块。如果你没有安装该模块,可以通过 `pip install websocket-client` 命令安装。
在实际应用中,你需要根据实际情况修改代码,建立与目标服务器的 WebSocket 连接,并按照协议规定的格式发送和接收消息。