B4J Question How to set up a simple websocket server

kostefar

Active Member
Licensed User
Longtime User
Dear All,

For reasons that I´ll skip explaining here (look here https://www.b4x.com/android/forum/threads/webview-continuously-receiving-data.95551/#post-603680 if you want the background) I need to set up a websocket server that I can communicate with on my intranet, simply sending frames to it that will processed.
So I´m trying to create a simple setup where I send a message every 3 seconds, and then I was hoping to find out how to manipulate it further.
But I get an error from the server side:

B4X:
java.lang.NullPointerException
    at anywheresoftware.b4j.object.WebSocketModule$Adapter.onWebSocketText(WebSocketModule.java:112)

Is anybody able to see what I´m doing wrong?

Thanks in advance, project attached.

PS: No, it won´t work to send this via UDP instead; they´re being sent from within a javascript.
 

Attachments

  • wsserverandclienttest.zip
    1.5 KB · Views: 297
Last edited:

Roycefer

Well-Known Member
Licensed User
Longtime User
On the client side, you will be better off using the WebSocketHandler class instead of the raw WebSocketClient. Instead of sending text messages back and forth, you will be raising events with parameters.
 
Upvote 0

kostefar

Active Member
Licensed User
Longtime User
On the client side, you will be better off using the WebSocketHandler class instead of the raw WebSocketClient. Instead of sending text messages back and forth, you will be raising events with parameters.

Thanks, but I found a solution now.
I wasn´t aware of the syntax for messages that needs to be followed. So I have this now:

B4X:
Sub timer_tick
'Dim m As Map
'm.Initialize
    'm.Put ("time", DateTime.Now)
    Dim json As JSONGenerator
'    json.Initialize(m)
'    Dim jsonstring As String = json.ToString
'    Log (jsonstring)
    'ws.SendText(jsonstring)
    Dim timestring As String = DateTime.now
    Dim m As Map
    m.Initialize
    m.Put("type", "event")
    m.Put("event","Device_Message")
    m.Put("params", timestring)
    Dim jg As JSONGenerator
    jg.Initialize(m)
    ws.SendText(jg.ToString)
End Sub

And in the Websock Class I have:

B4X:
Sub Device_Message(Params As Map)
Dim indstring As String = Params
    indstring = indstring.replace("(String) ","")
Log (indstring)

End Sub

I guess it can be done more elegantly than this, but I´m pretty ok with it!
 
Upvote 0
Top