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

I have used socket.io to connect the Android client to the node.js server and can send messages to the server, but I can't receive messages on the client. I really like the client

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 the following objects:

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

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

Then on the client:

     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 will never receive a message. Does anyone know why? thank you!

resolvent:

If you use nkzawa's socket.io library according to the documentation, you must use the runonuithread method to handle the inside of the call 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. The listener is an instance of emitter. Listener and must implement the call method. You will notice that call() is internally wrapped by activity #runonuithread(), because the callback is always called on another thread of the Android UI thread, so we must ensure that a message is added to view the UI thread

See this link for more information: native socket.io and Android

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>