Android Question WebSocket over https

woniol

Active Member
Licensed User
Longtime User
Is it possible to use B4A WS Library to connect to B4J server over https?
 

daemon

Active Member
Licensed User
Longtime User
Please share the code, I'll give it a try... I hope I'd be able to compile using the B4A library compiler tool.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Here:
B4X:
package anywheresoftware.b4a.objects;

import java.io.IOException;

import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BA.Events;
import anywheresoftware.b4a.BA.Hide;
import anywheresoftware.b4a.BA.Permissions;
import anywheresoftware.b4a.BA.ShortName;
import anywheresoftware.b4a.BA.Version;
import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketOptions;
import de.tavendo.autobahn.WebSocket.ConnectionHandler;

/**
 * Implementation of a WebSocket client.
 */
@Version(1.01f)
@ShortName("WebSocket")
@Events(values={"Connected", "Closed (Reason As String)", "TextMessage (Message As String)"})
@Permissions(values={"android.permission.INTERNET"})
public class WebSocketWrapper {
   private BA ba;
   private String eventName;
   @Hide
   public WebSocketOptions options;

   @Hide
   public WebSocketConnection wsc;
   /**
    * Initializes the object and sets the subs that will handle the events.
    */
   public void Initialize(BA ba, String EventName) {
     eventName = EventName.toLowerCase(BA.cul);
     this.ba = ba;
     wsc = new WebSocketConnection();
     options = new WebSocketOptions();
     options.setSocketConnectTimeout(30000);
     
   }
   /**
    * Tries to connect to the given Url. The Url should start with ws://.
    */
   public void Connect(String Url) throws WebSocketException {
     
     wsc.connect(Url, new ConnectionHandler() {

       @Override
       public void onBinaryMessage(byte[] payload) {
         
       }

       @Override
       public void onClose(int code, String reason) {
         if (wsc.isConnected())
           try {
             wsc.mTransportChannel.close();
           } catch (IOException e) {
             e.printStackTrace();
           }
         ba.raiseEventFromDifferentThread(WebSocketWrapper.this, null, 0, eventName + "_closed", false, new Object[] {reason});
       }

       @Override
       public void onOpen() {
         ba.raiseEvent(WebSocketWrapper.this, eventName + "_connected");
       }

       @Override
       public void onRawTextMessage(byte[] payload) {
         
       }

       @Override
       public void onTextMessage(String payload) {
         ba.raiseEvent(WebSocketWrapper.this, eventName + "_textmessage", payload);
       }
       
     }, options);
   }
   /**
    * Checks whether the connection is open.
    */
   public boolean getConnected() {
     return wsc.isConnected();
   }
   /**
    * Closes the connection.
    */
   public void Close() {
     wsc.disconnect();
   }
   /**
    * Sends a text message.
    *
    */
   public void SendText(String Text) {
     wsc.sendTextMessage(Text);
   }
   
}
 
Upvote 0

Firpas

Active Member
Licensed User
Longtime User
Hello everyone.

I'm writing a library to create conenexiones with wss WebSocket support socket.io ... and more.
It is based on this project: https://github.com/koush/AndroidAsync.

As you can see in my code, the library has two events.

B4X:
import com.koushikdutta.async.ByteBufferList;
import com.koushikdutta.async.DataEmitter;
import com.koushikdutta.async.callback.DataCallback;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpClient.WebSocketConnectCallback;
import com.koushikdutta.async.http.WebSocket;
import com.koushikdutta.async.http.WebSocket.StringCallback;

import android.util.Log;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BA.*;

@Events(values={"Connected", "TextMessage (Message As String)"})
@DependsOn(values=("androidasync-2.1.4"))
@ShortName("FMWebSocket")
@Version(1.0f)
@Author("Firpas")

@Permissions(values = {"android.permission.INTERNET"})

public class FMWebSocket {

    private BA ba;
    private String eventName;
    private WebSocket _webSocket = null;
   
    /**
    * Initializes the object and sets the subs that will handle the events.
    */
   public void Initialize(BA ba, String EventName) {
     eventName = EventName.toLowerCase(BA.cul);
     this.ba = ba;
   }

    public void Connect(String url){
        AsyncHttpClient.getDefaultInstance().websocket(url, "my-protocol",  webSocketCallback);
    }
   
    private WebSocketConnectCallback webSocketCallback = new WebSocketConnectCallback() {
        @Override
         public void onCompleted(Exception ex, WebSocket webSocket) {
            if (ex != null) {
                ex.printStackTrace();
                Log.w("B4A", Log.getStackTraceString(ex));
                return;
            }
            _webSocket=webSocket;
            //This event is triggered ok. :-)
            ba.raiseEvent(_webSocket, eventName + "_connected");
           
            webSocket.setStringCallback(new StringCallback() {
                public void onStringAvailable(String s) {
                    final String message = s;
                    Log.w("B4A", "Lib: " + message);
                    // message is ok but these events are not triggered. :-(
                    ba.raiseEventFromDifferentThread(_webSocket, null, 0, eventName + "_TextMessage", false, new Object[] {message});
                       //ba.raiseEvent(_webSocket, eventName + "_TextMessage", new Object[] {message});
                }
            });
           
            webSocket.setDataCallback(new DataCallback() {
                public void onDataAvailable(ByteBufferList byteBufferList) {
                    System.out.println("I got some bytes!");
                    // note that this data has been read
                    byteBufferList.recycle();
                }

                @Override
                public void onDataAvailable(DataEmitter arg0,
                        ByteBufferList arg1) {
                    // TODO Auto-generated method stub
                   
                }
            });
           
        }
    };
   
    public void SendText(String Text){
        if (_webSocket != null && Text.length()>0) {
             _webSocket.send(Text);
         }
    }
   
    public void Close(){
        _webSocket.close();
    }

    public boolean getConnected() {
        return _webSocket.isOpen();
    }

       
}

The "Connected" event is triggered well, but I can not fire the "TextMessage" event and do not know where my mistake is.

Any suggestions?

Thanks in advance.
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Upvote 0

Firpas

Active Member
Licensed User
Longtime User
B4X:
public class FMWebSocket {

    private BA ba;
    private String eventName;
    private WebSocket _webSocket = null;

but it isn't the problem
 
Upvote 0
Top