给你贴个可以运行的代码
``` 服务端
from flask import Flask
from flask_socketio import SocketIO, emit, join_room
from loguru import logger
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
tokenList = {}
@
app.route("/test")
def testConnect():
sid = tokenList["114514"]
data = {'from': 'server'}
# socketio.emit('newMission', data, namespace='/mission')
socketio.emit('newMission', data, to=sid, namespace='/mission')
return 'success'
@
socketio.on('register')
def register(data):
sid = data['sid']
print("服务器%s 尝试注册" % data["secret"])
emit('register', {"token": sid})
logger.debug("注册成功,token 为%s" % sid)
join_room(sid)
tokenList["114514"] = sid
@
socketio.on('message', namespace='/mission')
def message(data):
print(data) # {'from': 'client'}
# emit('response', {'from': 'server'})
# sleep(5)
# emit('response', "exit")
if __name__ == '__main__':
socketio.run(app, debug=True, host='127.0.0.1', port=8090)
```
``` 客户端
import socketio
sio = socketio.Client()
@
sio.on('connect')
def on_connect():
print('正在注册,请稍后')
# 获取 namespace sid, 发送给 server
sid = sio.get_sid('/mission')
sio.emit('register', {'secret': '114514', 'sid': sid})
@
sio.on('register')
def isReg(data):
print("receiver message from register ,当前 token 为", data['token'])
pass
@
sio.on("newMission", namespace='/mission')
def newMission(data):
print("get mission message data: ", data)
sio.connect('ws://localhost:8090')
sio.wait()
```
主要是获取到 namespace 后,把 namespace sid join room, 记录好 sid. 要 emit 的时候, 加上 namespace 和 roomId(sid)进行发送