简体   繁体   中英

How do I change the timeout for an opening a WebSocket?

Short and sweet: How do I tell a WebSocket to stop or 'close' after attempting to open after a while?

I'm currently working on a Kahoot like web app where players can connect with their phones to play. The game uses completely vanilla JavaScript to run everything in the background and uses WebSockets to communicate with the django-channels game server. The game plays fine except for in scenarios where a player accidentally locks their phone or switches apps and closes their WebSocket. I can easily open a new connection but for some reason, in mobile safari, WebSockets take FOREVER to give up connecting.

For example:

  1. A user connects on Wifi and opens a WebSocket
  2. User disconnects from Wifi and drops the WebSocket without calling .close and properly closing the connection
  3. User attempts to open new WebSocket without Wifi
  4. User then connects to Wifi while previous WebSocket is still trying to connect

In my testing, the second WebSocket will try to connect for at least a minute before finally giving in and failing. Only then can I attempt to reconnect again and just exaggerates the whole process of reconnecting the player.

So like I asked above: how can I shorten this process? Is there a way to make the WebSocket give up sooner or am I doing this the wrong way?

If I need to add any more information, please let me know. This is my first time posting.

Thanks a lot!

I do not see a connection timeout mentioned anywhere in the webSocket API specification , nor can I find any mention in any webSocket documentation. So, it appears you might have to implement your own. Here's one way to do that:

function connectWebSocket(url, timeout) {
    timeout = timeout || 2000;
    return new Promise(function(resolve, reject) {
        // Create WebSocket connection.
        const socket = new WebSocket(url);

        const timer = setTimeout(function() {
            reject(new Error("webSocket timeout"));
            done();
            socket.close();
        }, timeout);

        function done() {
            // cleanup all state here
            clearTimeout(timer);
            socket.removeEventListener('error', error);
        }

        function error(e) {
            reject(e);
            done();
        }

        socket.addEventListener('open', function() {
            resolve(socket);
            done();
        });
        socket.addEventListener('error', error);
    });
}

// Usage    
connectWebSocket(yourURL, 1000).then(function(socket) {
    socket.send("hello");
    // put other code that uses webSocket here
}).catch(function(err) {
    console.log(err);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM