Threads
Each WebSocket class instance runs in a different thread (in release mode). This allows many users to be connected at the same time.
CallSubDelayed was modified in B4J v2.00 to be executed on the target object thread. This allows us to safely call subs in other modules or instances.
In this example we have a code module named ChatShared. This module holds references to all the active connections and whenever there is a new message it uses CallSubDelayed to notify each of the instances about the new message:
'ChatShared code module
'notify each of the connected users about the new message
For Each c As Chat In connections.Values
CallSubDelayed2(c, "NewMessage", msg)
Next
'Chat WebSocket class
Sub NewMessage(Msg As String)
ChatTxt.RunMethod("append", Array As Object(Msg))
ws.RunFunction("scrollDown", Null)
ws.Flush
End Sub
The code in code modules will run in the main thread if we call it with CallSubDelayed.
In this example we call WebUtils methods directly as these methods do not rely on any shared data.