B4J Question WebSocket Client receive text

aaronk

Well-Known Member
Licensed User
Longtime User
Hi,

I am trying to learn WebSockets with B4J.

So far I have worked out how my B4J WebSocket Client can send the data to the server, but can't work out how to send the data back to the client that sent the message.

When the Client connects to the server I have got it to log 'Connected'.
I then made it so when I press a button to send the text hello to the server.

The server then receives this hello message. I then log the message but then I am trying to send something back to the client.

I can't work out what I have done wrong, or maybe I am doing it wrong.

Anyone know what I have done wrong ?

Server Code:
B4X:
'WebSocket class
Sub Class_Globals
    Private ws As WebSocket 'ignore
End Sub

Public Sub Initialize
  
End Sub

Private Sub WebSocket_Connected (WebSocket1 As WebSocket)
    ws = WebSocket1
    Log("Connect")
End Sub

Private Sub WebSocket_Disconnected
    Log("Disconnected")
End Sub

Sub Device_Message(Params As Map)
       Log("Device message: " & Params.Get("message"))

       If Params.Get("message") = "hello" Then
        'this section activates so I know the following code should run
        ws.RunFunction("ws_ServerTime", Array As Object(DateTime.Time(DateTime.Now)))
          ws.Flush
    End If
End Sub

Client:
B4X:
#Region Project Attributes
    #MainFormWidth: 600
    #MainFormHeight: 400
#End Region

Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
  
    Dim ws As WebSocketClient
  
    Private Button1 As Button
    Private TextField1 As TextField
    Private Button2 As Button
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("1") 'Load the layout file.
  
    MainForm.Show
  
    ws.Initialize("ws")
  
End Sub

Private Sub ws_Connected
    Log("Connected")
End Sub

Private Sub ws_Closed (Reason As String)
    Log("Close - " & Reason)
End Sub

Public Sub SendMessageToCloud(Msg As String)
    SendEventToServer("Device_MessageFrom", CreateMap("text": Msg))
End Sub

'Raises an event on the server. The Event parameter must include an underscore
Public Sub SendEventToServer(Event As String, Data As Map)
    Dim m As Map
    m.Initialize
    m.Put("type", "event")
    m.Put("event", Event)
    m.Put("params", Data)
    Dim jg As JSONGenerator
    jg.Initialize(m)
    ws.SendText(jg.ToString)
End Sub

Sub SendToServer
   Dim data As Map
   data.Initialize
   data.Put("message", TextField1.text)    ' textfield1.text = hello
   SendEventToServer("Device_Message", data)
End Sub

Sub ws_ServerTime(Params As List)
   'example of a server push message
   Log("Server Time: " & Params.Get(0))
End Sub

Sub Button1_Action
    ' connect to WebSocket server
    ws.Connect("ws://127.0.0.1:8888/api")
End Sub

Sub Button2_Action
    'Send message to server
    SendToServer
End Sub
 
Top