Reputation: 553
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.
Upvotes: 4
Views: 6294
Reputation: 5251
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.
Upvotes: 7