Search code examples
javascriptpythonwebsockettornado

Reconnect to the same Websocket


I have a client-server game. Server is in Python and uses Tornado:

main.py
app = web.Application([
    (r'/ws', Game),
])

if __name__ == '__main__':
    app.listen(config['port'])
    ioloop.IOLoop.instance().start()
...


game.py
class Game(websocket.WebSocketHandler):
...

Client uses JavaScript.

When Internet goes down I want client to try to reconnect to the same game, so that user could continue playing. I tried some examples from StackOverflow, but they create new connection and game starts over:

function startSocket() {
    ws = new WebSocket('ws://' + window.tornado.host + ':' + window.tornado.port + '/ws');
    ws.onopen = onSocketOpen;
    ws.onmessage = onSocketMessage;

    ws.onclose = function(event) {
        checkSocket();
    };  

    setInterval(checkSocket, 5000);
}

function checkSocket() {
    if (!ws || ws.readyState === WebSocket.CLOSED) {
        startSocket();
    }
}

How I can reconnect to the same socket? (sorry if term is incorrect)


Solution

  • Your problem isn't the connection, it is retaining the existing game state. Simply send a generated identifier to the client when the game starts which the client can use later to request the existing state when it is reconnecting. This id could be sent in the URL or using the socket when successfully connected. After this the server will know what data to send back. The server will either send the existing data (when received an id) or create a new game (when there was no id sent by the client).