【问题标题】:how to pass the callback function in node.js from android client如何从android客户端传递node.js中的回调函数
【发布时间】:2017-07-30 12:48:06
【问题描述】:

我想将数据从 android 客户端中的套接字发送到 node.js 服务器.. 我在服务器端做了什么:

     socket.on('new user',function(data,callback){
        console.log('ON new user');

      if(data in users ){
        callback(false);
       }else {
        callback(true);
        socket.nickname = data;
        users[socket.nickname]= socket;
            UpdateNickNames();
    }
});

在我的客户端 android 上:

         import io.socket.client.IO;
        import io.socket.client.Socket;
       import io.socket.emitter.Emitter;

 public class MainActivity extends AppCompatActivity {
  private static final String TAG = "MainActivity";
EditText edt;
Button btn;
boolean msg;
private Socket mSocket;
{
    try {
        mSocket = IO.socket("http://192.168.1.101/");
        Log.v(TAG,"fine");
    } catch (URISyntaxException e) {
        Log.v(TAG,"Error..... "+e.getMessage());
        e.printStackTrace();
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mSocket.connect();
    edt=(EditText)findViewById(R.id.editText);
    btn=(Button)findViewById(R.id.button);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            attemptSend();
        }
    });
}
private void attemptSend() {
    String message = edt.getText().toString().trim();
    if (TextUtils.isEmpty(message)) {
        return;
    }


    mSocket.emit("new user", message, true);
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}

但它因错误而崩溃: 投掷者; // 未处理的 'error' 事件 ^ TypeError: callback is not a function

【问题讨论】:

    标签: javascript android socket.io


    【解决方案1】:

    我相信您的服务器端代码看起来不错。问题出在客户端......当您发出“新用户”事件时,请确保它是您作为参数传递的函数,而不是您传递了一个布尔值(true)。试试这个,

    mSocket.emit("新用户", 消息, 回调);

    另外,根据你从服务器端得到的回调结果,你做一些事情,否则你做其他事情..

    希望这会有所帮助!

    【讨论】:

    • aha ...你的意思是这样的:public void callback(boolean x) { boolean y; y=x; if(y== blablabla ){ // 代码放在这里 }else{ // 代码放在这里 } }
    【解决方案2】:

    我在这里找到了解决方案:

                mSocket.emit("new user", message, new Ack() {
                @Override
                public void call(Object... args) {
                  //Code goes here 
                }
        });
    
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-28
      • 2015-03-22
      • 2020-07-10
      • 1970-01-01
      • 2016-05-11
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 2016-06-17
      相关资源
      最近更新 更多