B4A Library WebSocket Client Library

Discussion in 'Additional libraries, classes and official updates' started by Erel, Apr 23, 2014.

  1. Erel

    Erel Administrator Staff Member Licensed User

    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:
    Code:
    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.

    Code:
    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

    Code:
    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.basic4ppc.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.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
     

    Attached Files:

    Last edited: Apr 16, 2019
  2. Don Oso

    Don Oso Active Member Licensed User

    Wow ... Excellent ..

    One question... this library support Socket.io?

    Thanks Erel!
     
  3. Erel

    Erel Administrator Staff Member Licensed User

    This library works with WebSockets. I haven't tested it with Socket.io however Socket.io should use real WebSocket when they are supported so I believe that it should work.
     
  4. woniol

    woniol Active Member Licensed User

    Thanks Erel,
    I was waiting for it.

    Will it work with b4j?

    I have problems running in Release mode. I doesn't connect.
    Works fine in Debug mode.
     
    Last edited: Apr 23, 2014
  5. woniol

    woniol Active Member Licensed User

    When I run it i Debug mode and the server side is not running I get this in log while trying to connect:

     
  6. Erel

    Erel Administrator Staff Member Licensed User

    It is missing the internet permission. It will be fixed tomorrow (as well as the thread issue).

    You cannot use this library from B4J. The open source project is based on Android API.
     
  7. woniol

    woniol Active Member Licensed User

    Ok,
    After adding
    Code:
    AddPermission(android.permission.INTERNET)
    to the Manifest it works fine in Release
     
  8. billzhan

    billzhan Active Member Licensed User

    Works great on android 4.1. What a pity that it doesn't work with B4J
     
  9. dealsmonkey

    dealsmonkey Active Member Licensed User

    Thankyou for this, timing is perfect for a new client project :)
     
  10. MaFu

    MaFu Well-Known Member Licensed User

    I tried the sample app: compiling with Debug (legacy) settings and running in emulator (Nexus 4 AVD).
    But on connect the following error log occurs:
     
  11. Erel

    Erel Administrator Staff Member Licensed User

    See post #6. It will be fixed later today.
     
  12. bluedude

    bluedude Well-Known Member Licensed User

    I guess the biggest benefit would actually be that it would run with things like Socket.io, PubNub etc. Not tested it, maybe it works.
     
  13. Erel

    Erel Administrator Staff Member Licensed User

    V1.01 was uploaded to the first post. It fixes the missing permission issue and the "wrong thread" error.
     
  14. wl

    wl Well-Known Member Licensed User

    Hi Erel,

    Is there some kind of heartbeat, so that when the connection drops (tend to occur every once and a while on a mobile device :) this can be detected and a new connection initiated ?

    Thanks
     
  15. Erel

    Erel Administrator Staff Member Licensed User

    You can implement one in your code. See this example: Custom WebSocket Based Push Framework

    (Tomorrow I will upload a new version of this example that fixes several issues that still exist)
     
  16. little3399

    little3399 Active Member Licensed User

    Does the WebSocket can be used to implement FileTransfer between B4A and WEB ?
     
  17. Erel

    Erel Administrator Staff Member Licensed User

    What do you mean with WEB? Are you referring to any specific web server?
     
  18. Douglas Farias

    Douglas Farias Expert Licensed User

    erel i have this error when i try load the sample server
     
  19. Erel

    Erel Administrator Staff Member Licensed User

    This is not an error. The server prints information to StdErr so it shows in red.
     
    Douglas Farias likes this.
  20. LucaMs

    LucaMs Expert Licensed User

    I get a strange behavior.

    The server (b4j) runs some routines on the client (device) in the right way.
    For example:
    Code:
    ws.RunFunction("RaisedByServer_NewNickOK"Array As Object(Nick))
    ws.Flush

    In the case in which the routine is not present in the client code, I rightly get an error.

    Only in one of these calls, the routine of the client does not run and I do not get error messages.

    The method of the call is identical and also the modules are the same!

    SERVER - wshPlayer
    Code:
    Private Sub RunOnClient_NewNickOK(Nick As String)  '  <---- THIS IS OK
        ws.RunFunction("RaisedByServer_NewNickOK"Array As Object(Nick))
        ws.Flush
    End Sub

    Public Sub RunOnClient_PlayerJoinsRoom(msg As String)
    Log("RunOnClient_PlayerJoinsRoom"' <--- I get this log
        ws.RunFunction("RaisedByServer_PlayerJoinsRoom"Array As Object(msg))
        ws.Flush
    End Sub

    CLIENT - PlayerHandler
    Code:
    Public Sub RaisedByServer_NewNickOK(Params As List)  ' <---- THIS IS OK, RUNS
        Private Nick As String = Params.Get(0)
        CallSubDelayed2(CallBack, EventName & 
    "_NewNickOK", Nick)
    End Sub

    Public Sub RaisedByServer_PlayerJoinsRoom(params As List)
    Log("RaisedByServer_PlayerJoinsRoom"' <--- I DON'T get this log
    End Sub

    I realize that this explanation is poor; on the other hand I can not post both projects.


    I hope this has happened to you :)
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice