5

In socket.io the disconnect event doesn't fire when the transport xhr-polling is active. If I switch the transport to websockets it works fine, but in xhr-polling its doesn't work.

/* Basics */
var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

server.listen(1337, null);

io.set('transports', ['xhr-polling']);

// routing
app.get('/', function (req, res) {
    res.sendfile("index.html");
    app.use(express.static(__dirname));
});

io.sockets.on('connection', function (socket) 
    socket.on('disconnect', function() {
        console.log('LOL');
    });
});

In the following code the disconnect doesn't fire, but if I delete the line -
io.set('transports', ['xhr-polling']);
It works perfectly, so why it doesn't work with xhr-polling? but only with websockets?

How can I fix this? Am I missing something?

Thanks in Advance ;)

4

2 回答 2

1

我遇到了同样的问题,然后我在客户端套接字中使用了选项 {'sync disconnect on unload' : true}:

var socket = io.connect('http://yourServerDomain.com', {'sync disconnect on unload' : true});

它强制套接字立即发送断开连接事件。

于 2015-04-02T12:54:01.467 回答
1

使用 XHR-Polling 无法立即检测到断开连接,因为客户端会为每条消息重复连接。

Socket.io 通过在 xhr 轮询套接字上设置不活动超时来解决这个问题。

这是相关文档:https ://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO

请参阅heartbeat interval配置选项。默认值为 25 秒。

Websocket 在浏览器和服务器之间维护一个持久的 tcp 套接字,因此 socket.io 通常可以在套接字断开连接时立即检测到。

于 2013-07-17T01:04:46.610 回答