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:
Remember that sessions are stored in the server side.
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