如何使用socket io从服务器接收消息

时间:2012-09-10 17:07:42

标签: android socket.io

我正在使用由Gottox.i编写的Socket.IO-Client for Java制作一个Android应用程序知道如何向服务器发送消息但我想知道如何从服务器接收消息或获取响应 这是我的代码示例

 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!");


    } 

2 个答案:

答案 0 :(得分:2)

我通过此方法收到消息

  @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());
        }

您可以使用socket.io标记检查日志服务器响应

答案 1 :(得分:0)

IOCallback中的onMessage方法可以通过参数“String data”获取消息Server 如果此方法永远不会被消息服务器发送,则可能是您的连接不活动