Connecting to a Socket.IO server from Android
Socket.IO has a specified protocol on the top of WebSocket, so you have to use a client for Socket.IO, not for WebSocket. There are some Socket.IO clients in Java and Android, but you will find socket.io-java-client is the best way to go.
https://github.com/Gottox/socket.io-java-client
Since socket.io-java-client doesn’t support Maven, you have to use a forked version of it if you use with Maven. The forked version is slightly different than the original. (e.g., It uses Gson instead of org.json package)
https://github.com/fatshotty/socket.io-java-client
Simple Usage
An example to send and receive events. The following is a code of a simple echo server in Node.
io.sockets.on('connection',function(socket){
socket.on('echo',function(data){
socket.emit('echo back', data);});});
The next is a Java code to connect to the server from Android. The usage of the client is similar to the Socket.IO client for JavaScript. You can send a message via SocketIO#emit
or SocketIO#send
method, and can receive data via IOCallback#on
and IOCallback#onMessage
callbacks.
SocketIO socket =newSocketIO("http://127.0.0.1:3001");
socket.connect(newIOCallback(){@Overridepublicvoid on(Stringevent,IOAcknowledge ack,Object... args){if("echo back".equals(event)&& args.length >0){Log.d("SocketIO",""+ args[0]);// -> "hello"}}@Overridepublicvoid onMessage(JSONObject json,IOAcknowledge ack){}@Overridepublicvoid onMessage(String data,IOAcknowledge ack){}@Overridepublicvoid onError(SocketIOException socketIOException){}@Overridepublicvoid onDisconnect(){}@Overridepublicvoid onConnect(){}});
socket.emit("echo","hello");
Headers and Cookie
This is an example to send cookie when handshaking.
String host ="http://127.0.0.1:3001";String cookie =CookieManager.getInstance().getCookie(host);SocketIO socket =newSocketIO(host);
socket.addHeader("Cookie", cookie);
socket.connect(newIOCallback(){...});
Acknowledge
Acknowledge is the way to get a response corresponding to a sent message. The following is a code snippet for server-side.
io.sockets.on('connection',function(socket){
socket.on('echo',function(data, callback){
callback(data);});});
The next is for client-side. Use an instance of an IOAcknowledge implementation with SocketIO#emit
orSocketIO#send
method.
IOAcknowledge ack =newIOAcknowledge(){@Overridepublicvoid ack(Object... args){if(args.length >0){Log.d("SocketIO",""+ args[0]);// -> "hello"}}}
socket.emit("echo", ack,"hello");