WebSockets on Android with socket.io on Android

I want to use the NodeJS + SocketIO application with a new Android-based client application. I am currently using okhttp3 for Websockets on Android. but I want to use WebSockets with socket.io.

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

+4
source share
1 answer

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

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 works great against Node.js + Socket.io with version 0.8.3 .

Socket singletonclass:

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;
    }
}

Primary use, onConnectevent:

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();

Github .

+4

Source: https://habr.com/ru/post/1688800/


All Articles