简体   繁体   中英

Passing function as parameter from Java to socket.io server

In javascript, you can do the following on the client side:

socket.emit('get country', function(country) {
    console.log(country);
});

Where the server side is:

socket.on('get country', function(fn) {
    fn(country);
});

And this will result in logging the value of "country" from the server on the client side.

In android/Java if you do the following on the client side:

interface MyCallbackInterface {
    void getCountry(String country);
}


socket.emit("get country", new MyCallbackInterface() {
    @Override
    public void getCountry(String country) {
        Log.i("log", country);
    }
});

Where the server side is still:

socket.on('get country', function(fn) {
    fn(country);
});

You get an error: "TypeError: string is not a function." When debugging the value of fn on the server side I get a string like this: com.abc.abc.criteria$2@20cb82cd, where com.abc.abc.criteria is the fully qualified name of the activity that has the Java client side code.

Is it possible to pass a callback function as a parameter from Java to socket.io server? And if so, how?

try:

socket.emit('get country', new Ack() {
  @Override
  public void call(Object... args) {
    String country = (String)args[0];
    Log.i("log", country);
  }
});

You can use only Ack interface as callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM