Python 的 socket.io 库可以用来建立客户端和服务器之间的 WebSocket 连接。接收服务器的消息的方法是使用 on
方法来注册回调函数。
以下是一个简单的例子:
import socketio
# 建立连接
sio = socketio.Client()
sio.connect('http://localhost:3000')
# 注册回调函数
@sio.on('message')
def on_message(data):
print('收到服务器消息: ', data)
# 向服务器发送消息
sio.emit('message', {'hello': 'world'})
上面的代码会连接到本地的服务器 (localhost:3000
),然后注册一个回调函数来接收来自服务器的 "message" 事件。当服务器发送了 "message" 事件时,客户端会自动调用 on_message
函数来处理这个事件。
你也可以使用 sio.on
方法来注册其他的事件,比如 "connect" 事件、"disconnect" 事件等。