B4J Tutorial [server] Automatic Reconnecting WebSocket

When working with WebSocket handlers the client maintains an online connection. The connection is expected to be kept alive for as long as needed.

However there are cases where the connection can be temporary broken. Especially when the client is a mobile browser.

Using the Reconnecting-WebSocket open source project the client can automatically try to reconnect.

See this video for an example. Pay attention to the server time updates.


In order to enable this feature you need to:
1. Use b4j_ws.js v0.91+ (open the file with a text editor to see the version)
2. Copy reconnecting-websocket.js to the www folder.
3. Add <script src="/reconnecting-websocket.js"></script> to the html file. Note that you don't need to add this to all handlers. Only to those that should use a reconnecting websocket.

Both files are available in the attached project (Objects\www).

The server doesn't distinguish between an automatic reconnection to a regular connection. In both cases a new WebSocket handler instance is created.
You can use the HttpSession to restore the previous state.

For example:
B4X:
Private Sub WebSocket_Connected (WebSocket1 As WebSocket)
   Log("Connected")
   ws = WebSocket1
   Dim session As HttpSession = ws.UpgradeRequest.GetSession
   If session.HasAttribute("state") = False Then
     state.Initialize
     state.Number = Rnd(1, 101)
     session.SetAttribute("state", state) 'sets a reference to the state object.
     Log($"Creating new state. Number = ${state.Number}"$)
   Else
     state = session.GetAttribute("state")
     Log($"Reusing previous state. Number = ${state.Number}"$)
   End If
'...
End Sub
Remember that sessions are stored in the server side.
 

Attachments

  • GuessMyNumberWithReconnection.zip
    9.4 KB · Views: 1,462

vfafou

Well-Known Member
Licensed User
Longtime User
Hello, Erel! Is this applicable to Custom WebSocket Framework?
I ask you because I see that you refer only to browser connections and not to device connections.

Thank you in advance.
 
Last edited:

vfafou

Well-Known Member
Licensed User
Longtime User
It is only relevant for browsers. The client in the "custom websocket framework" already implement a similar feature where a timer is used to reconnect.
Some times, it's occuring the following problem:
It is possible to have an internet line problem to my server.
The connections with the tablets, may totally be recovered but there is an option that may will be semi-recovered.
I have noticed that after a server internet disconnection, I have communication from tablets to server, but the server cannot send anything to tablets!
Do you have any suggestion? :)
 

ValhallSW

Member
Licensed User
Longtime User
I would like to see this example, Guess My Number, as a native B4A-application, not just in a browser
 
Top