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,582
  • ClientExample.zip
    8.3 KB · Views: 4,034
  • WebSocket.zip
    39.6 KB · Views: 2,260
Last edited:

TAK

Member
Licensed User
Longtime User
Don't confuse the server code (B4J) with B4A code.
ok, i just would like to unterstand how it works, to learning B4A and B4J faster.
What is the timer1 doing? Connecting the Server with client every 1000ms?
I saw the StartMessageLoop several times but stil dont really unserstand what it is doing.

thx :)
 

sasidhar

Active Member
Licensed User
Longtime User
Hi,

The example is working well for me on my local computer. Once I deployed at server where I have Public IP, Jar file could not run. Getting error while running Jar file.

Apart from Jar file anything need to implement at server.

Please help.

Below error I got while executing Jar file.

D:\New Folder>java -jar result.jar
2015-05-16 09:20:07.381:INFO::main: Logging initialized @400ms
2015-05-16 09:20:07.663:INFO:eek:ejs.Server:main: jetty-9.1.z-SNAPSHOT
2015-05-16 09:20:07.725:WARN:eek:ejh.MimeTypes:main: java.util.MissingResourceExcep
tion: Can't find bundle for base name org/eclipse/jetty/http/encoding, locale en
_GB
2015-05-16 09:20:07.803:INFO:eek:ejsh.ContextHandler:main: Started o.e.j.s.ServletC
ontextHandler@51016012{/,file:/D:/New%20Folder/www,AVAILABLE}
2015-05-16 09:20:07.819:INFO:eek:ejs.AbstractNCSARequestLog:main: Opened D:\New Fol
der\logs\b4j-2015_05_16.request.log
2015-05-16 09:20:08.210:INFO:eek:ejs.ServerConnector:main: Started ServerConnector@
5ba23b66{HTTP/1.1}{0.0.0.0:51042}
2015-05-16 09:20:08.210:INFO:eek:ejs.Server:main: Started @1285ms


Thanks
Sasidhar





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.

View attachment 24449

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.
 

ArminKH

Well-Known Member
@Erel
I dont know this is a bug or not but i think thats better if i report this
Please follow this steps:
1-Run your server on local host(created by b4j)
2-click on connect button on your client side
Now you see the is trying to connect to server
3- turn on your phone wifi hotspot and connect your pc to this network
Now you see your app connect to the server and wsh_connected event raised
4-turnoff your internet connection on pc (not turn off your wifi hotspot)
now you see _disconnected event raised on server side but wsh_closed not raised on client side and our app stil is connected to server without network connection
Why?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
The disconnected event is raised from the network driver. There maybe cases where the device mistakenly thinks that is is connected.

The solution for such issues is to use a "heart beat" mechanism to automatically close the connection when there is no data. You can see it in this example: Custom WebSocket Based Push Framework
 

ArminKH

Well-Known Member
can we send and recieve files or pictures between client and server over websocket by using this lib?how?
 

ArminKH

Well-Known Member
This library allows you to send strings between the client and the server. You can encode the images with base64 encoding though it will not be very efficient.
Thats not any limits on size?(large image)
What about other type of files such as music or zip files????
 
Last edited:

ArminKH

Well-Known Member
It doesn't matter whether it is an image or any other file. I don't recommend you to use this method for non-small files. Use regular server handler instead.
I am not familar with regular server handler
Whats your aim?
My search came up with noting for this
Thanx
 

ArminKH

Well-Known Member
If is possible please give me a relevant link on this forum
 

ArminKH

Well-Known Member
I see all of this many times
At some of them u use httputils on both side
Or use jnetwork + async stream
Or use connection between 2 device over wifi or bluetooth
Ok erel thank u
Every time i ask a question again i was more confused
If u want to help me please answer my questions at this thread

https://www.b4x.com/android/forum/t...ext-messages-between-client-and-server.54506/

Stillllllll i dont know what is regular server handler
I know this ide is free and thank u for free support but i am so begginer erel and i want to learn
If i dont understand thats not matter but if i dont ask thats soooooooo defect
Excuse 4 my english
Thanx
 
Status
Not open for further replies.
Top