重新连接成功时,为什么socket.io客户端重新发送脱机消息?

时间:2019-02-13 02:39:31

标签: node.js socket.io

我正在使用socket.io进行聊天。当客户端脱机时(只需关闭wifi),我仍然通过该消息向服务器发送一条消息(名为脱机消息A),该消息将无法成功发送。过了一会儿,客户端将收到断开连接事件,忽略该事件,我仍然向服务器发送消息(名为脱机消息B)。完成上述操作后,我打开wifi,客户端将重新连接成功。好的,问题是客户端重新连接成功后,服务器将收到所有脱机消息(A,B)。我无法弄清楚,它是如何从脱机状态重新成功连接socket.io的。

我知道脱机消息B如the question中所述存储在sendBuffer中。客户端重新连接成功后,客户端将在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);
});

如我所见,服务器将不会收到脱机消息,但是当客户端重新连接成功时,服务器会收到所有脱机消息。

1 个答案:

答案 0 :(得分:0)

基于socket.io code的发射:

if (this.connected) {
    this.packet(packet);
} else {
    this.sendBuffer.push(packet);
}

因此,offline messages A将被推送到sendBuffer,然后offline messages B将被推送到sendBuffer,然后当套接字再次连接时,sendBuffer将被发送到服务器。

相关问题