1

我正在使用 Gottox 编写的用于 Java 的 Socket.IO-Client 制作一个 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!");


    } 
4

2 回答 2

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 标签在日志中检查服务器响应

于 2013-07-12T02:42:30.077 回答
0

IOCallback 中的 onMessage 方法可以获取参数“String data”发送的消息服务器 如果该方法从未被消息服务器发送触发,则可能您的连接不活跃

于 2013-11-18T07:57:55.570 回答