簡體   English   中英

socket.io 如何通過 android 上的同步調用獲得響應?

[英]How socket.io get response with synchronous call on android?

我正在用socket.io-client-java編寫一個android聊天應用程序。我想首先檢查客戶端用戶是否存在。所以我需要向服務器url發送一個像“user/exist”這樣的命令並得到響應服務器。我需要等待服務器響應然后可以進入下一步。但是socket.io使用異步回調。為了獲得同步響應,我只知道Furture和Callable。所以我嘗試了使用如下代碼的方式:

//this is request method using socket.io
public JSONObject request(final String method,final String url,final JSONObject data){
    final JSONObject responseObj = new JSONObject();
    if (mSocket.connected()) {
             mSocket.emit(method, reqObj, new Ack() {
                @Override
                public void call(Object... objects) {
                    System.out.println("get Ack");
                    try {
                        responseObj.put("body", (JSONObject) objects[0]);
                    }catch (JSONException e){
                        e.printStackTrace();
                    }
                }
            })
         }
}
//this is Callable call implement
 @Override
    public JSONObject call(){
      return request("get","https://my-chat-server/user/exist",new JSONObject());
}

//this is call method in activity
        ExecutorService executor = Executors.newCachedThreadPool();
        Future<JSONObject> response = executor.submit(mApiSocket);
        executor.shutdown();
        JSONObject respObj = new JSONObject();
        JSONObject respBody = new JSONObject();
        try {
            respObj = response.get();
            respBody = respObj.getJSONObject("body");
        }catch (ExecutionException e){

        }catch(InterruptedException e1){

        }catch(JSONException e2){

       }

但它不起作用。respObj 為空。 我怎樣才能得到同步的響應? 我是java的新手,原諒我可憐的中文英語。 任何幫助,將不勝感激!

我知道 js 可以使用 Promise 並等待如下:

//request method
static request(method, url, data) {

    return new Promise((resolve, reject) => {

        this.socket.emit(method,
            {
                url: url, 
                method,
                data, 
            },
            async (res) => {
                if (res.statusCode == 100) { 
                    resolve(res.body, res); 
                } else {
                    throw new Error(`${res.statusCode} error: ${res.body}`);
                    reject(res.body, res);
                }
            }
        )

    })

}
//call method
response = await mSocket.request('get','https://my-chat-server/user/exist', {
            first_name: 'xu',
            last_name: 'zhitong',

        });

我不確定這是最好的方法,但我們可以等待回調如下:

@Nullable
Object[] emitAndWaitForAck(@NotNull String event, @Nullable Object[] args,
                           long timeoutMillis) {
    Object[][] response = new Object[1][1];
    Semaphore lock = new Semaphore(0);

    socketClient.emit(event, args, ackArgs -> {
        response[0] = ackArgs;
        lock.release();
    });

    try {
        boolean acquired = lock.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
        if (acquired) {
            return response[0];
        }
    } catch (InterruptedException ignored) {
    }

    return null;
}

假設您的 socket.io 服務器返回一個包含正文(或 null)的參數,您可以這樣稱呼它:

String method = "get";
String url = "https://my-chat-server/user/exist";
long timeoutMillis = 5000;
Object[] args = emitAndWaitForAck(method, new String[]{url}, timeoutMillis);
JSONObject response = (JSONObject) args[0];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM