Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

node.js - socket.io xhr-polling disconnect event

I have a socket.io node script with:

socket.on('disconnect', function(data) {    
  console.log('disconnect!');
});

When I connect with Chrome / Safari and close the page, I see 'disconnect!' in my server console.

However, when I connect with my iPhone and close the page, I don't see this message. I see debug - xhr-polling closed due to exceeded duration

How do I receive the disconnect event with iOS?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Socket.io switches to the xhr-polling transport when you are viewing the page in your iPhone. This might be caused by the configuration of socket.io or because the browser in your iPhone does not (fully) support websockets.

The xhr-polling implementation in socket.io does not emit disconnect event when the connection is closed, see github issue #431. You can reproduce this issue in your Chrome browser by forcing the socket.io server to use the xhr-polling transport only:

// the server side
var io = require('socket.io').listen(httpServer);
io.set('transports', ['xhr-polling']);

Good news: you can ask socket.io's client to notify the server about disconnect by turning on the sync disconnect on unload flag:

// the browser (HTML) side
var socket = io.connect('http://localhost', {
  'sync disconnect on unload': true
});

Warning: this option can worsen the user experience when the network and/or your server are slow, see this pull request for more information.

UPDATE

According to socket.io force a disconnect over XHR-polling, setting sync disconnect on unload might not be enough to fix the problem on iPhone/iPad.

As you can see in socket.io-client source code, sync disconnect on unload sets up a listener for beforeunload event, which is not supported by iOS Safari according.

The solution is probably to fix socket.io-client to listen for both unload and pagehide events, because the unload event may not work as expected for back and forward optimization. Use the pageshow and pagehide events instead. [Apple Web Content Guide].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...