简体   繁体   English

将函数作为参数从 Java 传递到 socket.io 服务器

[英]Passing function as parameter from Java to socket.io server

In javascript, you can do the following on the client side:在 javascript 中,您可以在客户端执行以下操作:

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:在 android/Java 中,如果您在客户端执行以下操作:

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."你得到一个错误:“TypeError:字符串不是一个函数。” 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.在服务器端调试 fn 的值时,我得到如下字符串:com.abc.abc.criteria$2@20cb82cd,其中 com.abc.abc.criteria 是具有 Java 客户端的活动的完全限定名称代码。

Is it possible to pass a callback function as a parameter from Java to socket.io server?是否可以将回调函数作为参数从 Java 传递到 socket.io 服务器? 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.您只能使用Ack接口作为回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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