B4J Question b4j websocket questions

ilan

Expert
Licensed User
Longtime User
hi,

i have 2 questions (for now) about websockets.

1, is it ok to use a Server Handler event inside a websocket class?

2, i am still not sure when i should call the ws.Flush() method, would be good to get an example when i should call Flush and when not.




thanx
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
1) Not sure what you mean. More information...

2) ws.Flush is needed after the server finished sending messages to the client. It is only needed in cases where the server messages are not sent as a response to a client event.
Example: https://b4x.com:51041/guessmynumber_ws/index.html
There is a ws.Flush call in the timer that updates the "server time" string.
 
Upvote 0

ilan

Expert
Licensed User
Longtime User
1) Not sure what you mean. More information...


B4X:
'WebSocket class
Sub Class_Globals
    Private ws As WebSocket
End Sub

Public Sub Initialize
    
End Sub

Private Sub WebSocket_Connected (WebSocket1 As WebSocket)
    ws = WebSocket1
    Log(ws.Secure)
End Sub

Private Sub WebSocket_Disconnected

End Sub

Sub Handle(req As ServletRequest, resp As ServletResponse)
    resp.ContentType = "text/html"
    resp.Write($"Server is running on port: ${Main.port}"$)
End Sub

B4X:
    srvr.AddWebSocket("/test/ws", "test_ws")
    srvr.AddHandler("/test", "test_ws", False)


ok thank you, so if i call a js function from the server i dont need to run ws.flush right?
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
1) Standard handler:
Client sends requests -> server answers with response.

Websocket handler:
Client connects to server and they stay connected for as long as needed.

There is no Handle event in WebSocket handlers.

2)
ok thank you, so if i call a js function from the server i dont need to run ws.flush right?
No. It depends on what triggered the event, where the relevant call is made.
If the event was triggered by the client then the pipe will be flushed automatically at the end of the event. If it is a server event (such as Timer_Tick) then you need to call ws.Flush yourself.
Don't think about it too much. There is no harm in calling ws.Flush even if it is not needed. This is different than waiting for Future.Value incorrectly. In the later case you are pausing the connection until the round trip is completed.
 
Upvote 0

Star-Dust

Expert
Licensed User
Longtime User
Websocket handler:
Client connects to server and they stay connected for as long as needed.

There is no Handle event in WebSocket handlers.
I would like to add that jServer handles webSocket stream with jQuery that's why it doesn't need Handler. What is received by the client is intercepted by the events of the jQuery elements.
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…