0

I am creating an application using Flask-SocketIO at the server side and a javascript Socket.IO client. (There will also be a Python client later). I want to ensure users are authenticated before they connect to the web socket server.

I have created a PHP login form to check the username and password. If these are valid then a unique token is returned and the token is also inserted into a table on the server. The token is passed to the client side javascript, where it is submitted with the request to create a web socket connection.

As I understand it Flask-SocketIO will simply accept the connection and I need to put my validation code under the @socketio.on('connect') decorator. (I assume a server based implementation of Socket.IO works in a similar way). Therefore my code checks the submitted token against the database table and if it is valid the web socket connection is simply allowed to happen. However if the token is not valid I issue a disconnect() command. The javascript client does not try the connection again, which is what I want in this scenario.

Here is where it gets tricky...

I would like to write a disconnect handler on the client side using socket.on('disconnect', function() { //do something }); to allow the user to reconnect when the socket is broken due to a poor mobile connection for example. How can I distinguish an accidental disconnection from an intentional one due to failed validation?

Conversely, I would like to alert the user to the fact that their validation process failed. But how to distinguish that from a scenario where the the socket is broken due to a poor mobile connection?

Lee Melbourne
  • 407
  • 5
  • 20

1 Answers1

1

I would like to write a disconnect handler on the client side using socket.on('disconnect', function() { //do something }); to allow the user to reconnect when the socket is broken due to a poor mobile connection for example.

There is no need for you to worry about reconnection. The Socket.IO client protocol includes reconnection support and will always try to reconnect when the connection is lost. To verify this, start your server, connect with a client, and then kill your server. A little bit later restart the server and you will see that in a matter of seconds the connection is reestablished.

Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152
  • Thanks Miguel, that is what is does alright. I do however need to display an informational message if either a) the initial login fails for some reason or b) the connection has dropped out temporarily. I can use a flag in my login function to detect when the initial submit fails (and clear the flag on success). All other scenarios I can assume are a dropout then. – Lee Melbourne May 06 '18 at 06:15