B4A Library WebSocket Client Library

Status
Not open for further replies.
This library allows you to create WebSocket connections with servers that support WebSockets.
It is based on this open source project: http://autobahn.ws/android/#

The main benefit of this library is that you can use it to communicate with B4J WebApp solutions.

The attached example includes a class named WebSocketHandler. With this class you can send events to the server and the server can send events to the device.

upload_2014-4-23_15-54-47.png


The server code is very simple:
B4X:
Sub Class_Globals
   Private ws As WebSocket
   Private timer1 As Timer
End Sub

Public Sub Initialize

End Sub

Private Sub WebSocket_Connected (WebSocket1 As WebSocket)
   ws = WebSocket1
   timer1.Initialize("timer1", 1000)
   timer1.Enabled = True
End Sub

Sub Timer1_Tick
'This method will raise the event on the device
   ws.RunFunction("ServerTime", Array As Object(DateTime.Time(DateTime.Now)))
   ws.Flush
End Sub

'event from the device
Sub Device_Message(Params As Map)
   Log("Device message: " & Params.Get("message"))
End Sub

Private Sub WebSocket_Disconnected
   timer1.Enabled = False
   Log("disconnected")
End Sub

Sending events to the server

WebSocketHandler.SendEventToServer takes the event name (not prefix in this case) and the data. The data is a Map that is converted to a JSON string. Note that the event name must include an underscore.

B4X:
Sub btnSend_Click
   Dim data As Map
   data.Initialize
   data.Put("message", EditText1.Text)
   wsh.SendEventToServer("Device_Message", data)
End Sub

Receiving events from the server

B4X:
Sub wsh_ServerTime(Params As List)
   'example of a server push message
   lblServerTime.Text = "Server Time: " & Params.Get(0)
End Sub

The sub name in this case is made of the prefix set in the Initialize method and the event name as received from the server. There should be a single parameter which is a List.

How to run this example?

You need the latest version of B4J: http://www.b4x.com/android/b4j.html
Download and run the server example.
You will need to open the firewall port (51042).

Set the address in the client code to match the server address.

Updates

v2.11: New Headers Map that can be used to add headers to the upgrade request (https://www.b4x.com/android/forum/threads/websocketclient-authorization.116574/#post-729213)
v2.10: New BinaryMessage event and SendBinary method.
v2.01: Fixes an issue with ssl disconnections that can throw the network on main thread exception.

v2.00: Based on the latest version of autobahn-java: https://github.com/crossbario/autobahn-java
Adds support for SSL connections (wss://) including using custom trust managers (mainly to accept self signed certificates).
SSL support is problematic on devices prior to Android 5. To support Android 4+ devices you need to update the security provider: https://www.b4x.com/android/forum/threads/ssl-websocket-client.88472/page-2#post-560044
 

Attachments

  • ServerExample.zip
    997 bytes · Views: 3,398
  • ClientExample.zip
    8.3 KB · Views: 3,821
  • WebSocket.zip
    39.6 KB · Views: 2,005
Last edited:

jimmyF

Active Member
Licensed User
Longtime User
v2.10: New BinaryMessage event and SendBinary method.

Is there a possibility of getting some code samples of using these methods and events?
The samples in Post #1 are dated 2014

Thanks
j
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
1. Binary messages are not relevant when communicating with B4J servers. Most WebSocket servers send and receive text messages so it is not a commonly used feature. It was requested by one of the forum members so I've added it.
2. The usage is very simple:
B4X:
WebSocket1.SendBinary(data)

Sub WebSocket1_BinaryMessage (Data() As Byte)
 Log("Binary message received.")
 'work with Data.
End Sub
 

jimmyF

Active Member
Licensed User
Longtime User
Binary messages are not relevant when communicating with B4J servers.

Okay, I see.
And thinking more about it, I don't really see a need for it in my situation.

Thanks.
 

warwound

Expert
Licensed User
Longtime User
I'm trying to use the latest version 2.1 of WebSocket library but compilation keeps failing with this error message:

B4A Version: 9.00
Parsing code. (0.02s)
Building folders structure. (0.03s)
Compiling code. (0.07s)
Compiling layouts code. (0.00s)
Organizing libraries. (0.00s)
Generating R file. (0.17s)
Compiling generated Java code. Error
B4A line: 81
Starter.WebSocketConnection1.SendBinary(NotifyCo
javac 1.8.0_211
src\mydomain\torrentsmanager\torrentsmanager.java:204: error: cannot find symbol
mostCurrent._starter._websocketconnection1.SendBinary(_notifycompletepacket);
^
symbol: method SendBinary(byte[])
location: variable _websocketconnection1 of type WebSocketWrapper

The offending code is:

B4X:
Sub DownloadQueue1_Ready
   Log("DownloadQueue1_Ready")
   Dim NextIncompleteTorrent As TorrentMeta=DownloadQueue1.GetNextIncompleteTorrent
   If NextIncompleteTorrent.IsInitialized Then
       BroadcastTorrentFile(NextIncompleteTorrent)
   Else
       Dim NotifyCompletePacket() As Byte=Array As Byte(Starter.COMMAND_NOTIFY_COMPLETE)
       
       Starter.WebSocketConnection1.SendBinary(NotifyCompletePacket)
       
   End If

End Sub

I've cleaned the project and restarted the b4a IDE but still compilation fails.
The b4a IDE shows i have version 2.1, and if i open the WebSocket.jar file in Java Decompiler i see the SendBinary(Data() As Byte) method exists in the wrapper.

What am i doing wrong?
 
Status
Not open for further replies.
Top