为什么socket.io客户端在重新连接成功时重新发送脱机消息?
我正在使用socket.io做聊天室。当客户端离线(只关闭wifi)时,我仍然通过消息发送消息(命名为离线消息A)到服务器将不会发送成功。一段时间后,客户端将收到disconnect事件,忽略它,我仍然向服务器发送消息(命名为脱机消息B)。完成上述操作后,我打开wifi,客户端将重新连接成功。好的,问题是服务器将在客户端重新连接成功后收到所有脱机消息(A,B)。我无法弄清楚这一点,它是如何从离线到重新连接socket.io的成功。
我知道离线消息B存储在sendBuffer中,如the question中所述。当重新连接成功时,客户端将重新发送sendBuffer中的消息,但为什么离线消息A仍然可以发送到服务器成功?我已编码显示此问题
/*
* Client side
*/
onClickSend = (value) => {
console.log('send message:', value)
this.socket.emit('chatMessage', value);
}
connect = () => {
if (!this.socket) {
console.log('connecting...')
this.socket = io(url, {
query: {
clientId: this.clientId
},
forceNew:true,
})
}
this.socket.on('connect',()=>{
console.log('connected');
})
this.socket.on('error',(err)=>{
console.log('error happen:',err);
})
this.socket.on('disconnect',(reason)=>{
console.log('disconnect event:', reason);
})
this.socket.on('reconnect',(e)=>{
console.log('reconnect success:' , e);
})
}
/*
* Server side
*/
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http)
const PORT = 40001;
io.on('connection', function(socket) {
const clientId = socket.handshake.query.clientId;
console.log('client come...', clientId)
socket.on('connect', function(data) {
console.log('user connects socket');
});
socket.on('disconnect', (reason)=>{
console.log('event disconnect: ', reason, clientId)
socket.removeAllListeners()
socket = null
})
socket.on('error', (err)=>{
console.log('error happen: ', err, clientId)
})
// the server will receive all the offline messages(message A, B)
// send after the network is down when the client
// reconnect success.
socket.on('chatMessage', (message)=>{
console.log('receive message: ', message, clientId)
io.emit('chatMessage', message)
})
});
http.listen(PORT, function() {
console.log('listening on *:', PORT);
});
我看到,服务器不会收到脱机消息,但是当客户端重新连接成功时,服务器会收到所有脱机消息。
回答如下:socket.io code基地发射:
if (this.connected) {
this.packet(packet);
} else {
this.sendBuffer.push(packet);
}
所以,offline messages A
将被推送到sendBuffer,然后offline messages B
将被推送到sendBuffer,然后当socket再次连接时,sendBuffer将被发送到服务器。