Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebSockets on Android with socket.io in Android

I am looking to leverage my NodeJS+SocketIO server application with a new Android based client Application. Currently I'm using a okhttp3 for Websockets in Android. but I want to use WebSockets with socket.io.

Has anyone else done this kind of library work against SocketIO with WebSocket. So please assistance me.

like image 788
Sumit Pansuriya Avatar asked Mar 08 '23 16:03

Sumit Pansuriya


1 Answers

Just add the following dependency to your Android build.gradle file:

compile('io.socket:socket.io-client:x.x.x') { //replace x.x.x by 0.8.3 or newer version
    exclude group: 'org.json', module: 'json'
}

It perfectly works against Node.js + Socket.io with 0.8.3 version.

Socket singleton class:

public class Socket {
    private static final String TAG = Socket.class.getSimpleName();
    private static final String SOCKET_URI = "your_domain";
    private static final String SOCKET_PATH = "/your_path";
    private static final String[] TRANSPORTS = {
        "websocket"
    };
    private static io.socket.client.Socket instance;

    /**
     * @return socket instance
     */
    public static io.socket.client.Socket getInstance() {
        if (instance == null) {
            try {
                final IO.Options options = new IO.Options();
                options.path = SOCKET_PATH;
                options.transports = TRANSPORTS;
                instance = IO.socket(SOCKET_URI, options);
            } catch (final URISyntaxException e) {
                Log.e(TAG, e.toString());
            }
        }
        return instance;
    }
}

Basic usage, onConnect event:

Socket socket = Socket.getInstance();

private Emitter.Listener onConnect = new Emitter.Listener() {
    @Override
    public void call(final Object... args) {
        //Socket on connect callback
    }
};
socket.on("connect", onConnect);
socket.connect();

For more info, visit developer Github page.

like image 59
AlexTa Avatar answered Mar 10 '23 11:03

AlexTa