Java – The Android client did not receive socket.io messages from the node.js server

The Android client did not receive socket.io messages from the node.js server… here is a solution to the problem.

The Android client did not receive socket.io messages from the node.js server

I’ve used socket.io to connect an Android client to a node.js server, and I’m able to send messages to the server but can’t receive messages on the client.
For the client, I do something similar

Log.i("MainActivity: ", "sending message");
    final JSONObject sdpObj = new JSONObject();

try {
        sdpObj.put("id","presenter");
        sdpObj.put("sdpOffer",localSdpOffer.description);
    } catch (JSONException e) {
        e.printStackTrace();
    }

LoginActivity.mSocket.emit("new message", sdpObj);

On the server I received an object like this:

 io.sockets.on('connection',function(socket){

socket.on('new message',function(message){
               some logic
          socket.emit('created',object); 

Then on the client side:

     LoginActivity.mSocket.on("created", new Emitter.Listener() {

@Override
        public void call(Object... args) {
            Log.i( TAG, "message back:received ");

User user = new User();
            JSONObject obj = null;
            try {
                obj = new JSONObject((String) args[0]);
                Log.i(TAG,"SdpAnswer: "+args[0].sdpAnswer+"id "+obj.sdpAnswer);

Log.i(TAG, "Instance of"+args[0].toString());
        }
    });
}

But for some reason, it never received the message.
Anyone know why this is so? Thanks!

Solution

If you use

nkzawa’s socket.io library according to the documentation, you must use the runonUIThread method to handle the internal structure of the calling method.

import com.github.nkzawa.emitter.Emitter;

private Emitter.Listener onNewMessage = new Emitter.Listener() {
    @Override
    public void call(final Object.. args) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                JSONObject data = (JSONObject) args[0];
                String username;
                String message;
                try {
                    username = data.getString("username");
                    message = data.getString("message");
                } catch (JSONException e) {
                    return;
                }

 add the message to view
                addMessage(username, message);
            }
        });
    }
};

This is what onNewMessage looks like. A listener is an instance of Emitter.Listener and must be implemented by calling a method. You’ll notice that the inside of call() is wrapped around Activity#runOnUiThread(), and this is because callbacks are always called on another thread of the Android UI thread, so we have to make sure to add messages to see what happens on the UI thread.

For more information, see this link:
Native Socket.IO and Android

Related Problems and Solutions