user1115684
user1115684

Reputation: 75

How to receive messages from server using socket io

i am making an android application using Socket.IO-Client for Java written by Gottox.i know how to send messages to the server but i want to know how to receive message or get response from the server here it is a sample of my code

 SocketIO socket=new SocketIO();
        try {
            socket = new SocketIO("http://41.69.21.123:1333/");
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        socket.connect(new IOCallback() {
            public void onMessage(JSONObject json, IOAcknowledge ack) {
                try {
                    tv.setText(json.toString(2));
                    System.out.println("Server said:" + json.toString(2));


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onMessage(String data, IOAcknowledge ack) {
                System.out.println("Server said: " + data);
            }

            public void onError(SocketIOException socketIOException) {
                System.out.println("an Error occured");
                socketIOException.printStackTrace();
            }

            public void onDisconnect() {
                System.out.println("Connection terminated.");
            }

            public void onConnect() {
                System.out.println("Connection established");
            }

            public void on(String event, IOAcknowledge ack, Object... args) {
                System.out.println("Server triggered event '" + event + "'");
            }
        });


        socket.send("Hello Server!");


    } 

Upvotes: 1

Views: 1573

Answers (2)

topxebec
topxebec

Reputation: 1427

The method onMessage in IOCallback can get message Server sended by the parameter "String data" If this method never tiggered by the message server send, maybe your connection is not alive

Upvotes: 0

fhamicode
fhamicode

Reputation: 2518

I receiving message at this method

  @Override
        public void on(String event, IOAcknowledge ack, Object... args) {
            System.out.println("Server triggered event '" + event + "'");
            //it comes with 3 parameters event, acknowledge and args
            //if you want to get args to String try this
              Object[] arguments = args;
            System.out.println("Args"+ arguments[0].toString());
        }

you can check server response at log with socket.io tags

Upvotes: 2

Related Questions