当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Handle Callbacks in Socket.io android client v1.4

问题描述:

I am not able to find any doc on how to properly handle Ack's and Events in the latest Socket.io (v1.4.3). All existing articles/question refer to older versions, especially the IOCallback class. But that class is not present on the latest version.

All I managed to find out till now is this :

To get Callbacks for Socket Events:

mSocket.connect();

mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

@Override

public void call(Object... args) {

//What to do here

}

})

  1. How do I handle the (Object... args). A little code example would be great.
  2. There seems to be more than a dozen events, do I have to handle all that separately? Or what is a good minimum set of events that I can implement to be informed about the connection?

To get callbacks for individual emit events :

mSocket.emit("payload", jsObj.toString(), new Ack() {

@Override

public void call(Object... args) {

//TODO process ACK

}

});

  1. Again, how am I supposed to process the (Object... args) ?

网友答案:

Well. I finally figured that out on my own.

How do I handle the (Object... args) on the EVENT_CONNECT listener's callmethod?

I haven't yet figured that out. But I'm lookin.

What is a good minimum set of events that I can implement to be informed about the connection

These three methods would be sufficient :

connect : Fired upon a successful connection.
connect_error : Fired upon a connection error.
connect_timeout : Fired upon a connection timeout.

Source : Socket.io Docs

how am I supposed to process the (Object... args) on an emit acknowledgement?

So I was digging through the docs and found this :

Server (app.js)

var io = require('socket.io')(80);
  io.on('connection', function (socket) {
    socket.on('ferret', function (name, fn) {
      fn('woot');
    });
  });

Client

socket.on('connect', function () { // TIP: you can avoid listening on `connect` and listen on events directly too!
    socket.emit('ferret', 'tobi', function (data) {
      console.log(data); // data will be 'woot'
    });
  });

So the args will be whatever the server sent as parameter into the callback. So this is how you would write Java client code for the above server code :

public void call(Object... args) {
  String response = (String)args[0]; //this will be woot
}

The param can also be JSON, or any of the supported datatypes in socket.io :

we send a string but you can do JSON data too with the org.json package, and even binary data is supported as well!

分享给朋友:
您可能感兴趣的文章:
随机阅读: