我想通过通信协议在Web客户端和后端服务器之间交换一对一的二进制/语音消息(“语音助手”,以实现客户端/服务器体系结构(Web浏览器客户端后端nodejs服务器) / bot“)。
我选择socketio作为网络套接字协议。这是基本的消息交换流程:
客户端到服务器的请求(拉模式)
向客户端的服务器通知(推送模式)
+----------------+ +------------------+
| | | |
+--+ | | | |
| | web browser | | | |
user 1 | +--------------> https | | |
| <--------------+ web server | | |
+--+ | for | | |
| static assets | | |
+--+ | | | |
| | web browser | | | cobot <--------+
user 2 | +--------------> +---> dialog +------+ |
| <--------------+ +---+ manager | | |
+--+ | socketio | | server | | |
| server | | logic | | |
| for audio / | | | | |
+--+ | video | | | | |
| | web browser | messages | | | | |
user N | +--------------> | | | | |
| <--------------+ | | | | |
+--+ | | | | | |
| | | | | |
+----------------+ +------------------+ | |
| |
也许有人可以将这种单播通信称为“单播”。 服务器端,这是接收以下内容的Web服务器的通常行为 来自某个客户的请求,并提供答复此请求的请求 客户。
我对于使用socketio API实现所描述的场景感到困惑。如果我对套接字的体系结构了解得很深:
// sending to sender-client only
socket.emit('messageType', 'message payload');
room
socketio概念是解决方案吗?我想分配一个房间 到每个客户端(用户),从而允许用户从不同的客户端进行连接 具有user_id
(room_id
=user_id
)的设备。在这种情况下,我 猜猜每个客户都必须加入他的“专用”房间。对吧?
UPDATE
阅读有趣的问题/答案:socket.io private message和How synchronise socketIO connection ID's on client and server?,我按照将房间关联到每个私有双向客户端/服务器通道的想法,绘制了此伪代码:The
client
://
// client side
//
const user_id = 'username'
const audioBlob = ... // audioChunks blob from MediaRecorder
// join the room with his user_id as name
socket.join(user_id)
// new user (= room) registration
// notify the server about this new connection
socket.emit('user_id', user_id)
...
// client send a message (request) to the server
// on room with name user_id, excluding sender as recipients
socket.broadcast.to(user_id).emit('audioMessage', audioBlob)
...
// client receive a message
// audio message received from server (the answer to the request)
socket.on('audioMessage', audioBlob =>
playAudio(audioBlob) )
:服务器
//
// server side
//
io.on('connection', socket => {
// pair/associate the socket with a room name
socket.on('user_id', user_id => {
socket.join(user_id)
// store somewhere association: {socket.id, user_id}
storeOnDB(socket, user_id)
})
// server receives a message from a client (pull request)
// the server elaborates the message
// and sends back to the user an answer
// (all clients in 'uid' room except sender, the server itself)
socket.on('audioMessage', msg => {
// retrieve the room name to which socket belongs
const user_id = getFromDB(socket)
socket.broadcast.to(user_id).emit('audioMessage', answerTo(msg))
})
}
...
// server sends an unsolicited/push message to a user
// (client socket on a room)
io.to('some uid').emit('some notification', data)
伪代码是否有意义/正确吗?