【发布时间】:2021-06-29 15:01:33
【问题描述】:
目前,我正在开发一个简单的 WebRTC 应用程序,其中客户端和服务器通过 RPC 相互通信。由于它的阻塞性质,本质上,这意味着如果我有一个请求并将其发送到服务器,我需要等到我收到响应。我有麻烦如何让客户端等到收到来自服务器的响应然后继续。最初,我做了一些类似Thread.sleep() 的事情,或者使用ExecutorService 和CountDownLatch,它们正在工作,但是程序的响应性确实降级了,我不知道客户端应该睡多长时间才能得到响应服务器。我想在这种情况下使用CompleableFuture,但我仍然不知道如何在我的上下文中使用它,非常感谢任何帮助!
这是客户端代码:
@Override
public CompletableFuture<SessionDescription> join(String sid, String uid, SessionDescription offer) {
String uuid = UUID.randomUUID().toString();
JsonRpcRequestMessage rpcMsg = new JsonRpcRequestMessage();
rpcMsg.setJsonrpc("2.0");
rpcMsg.setId(uuid);
rpcMsg.setMethod("join");
Map<String, Object> params = new HashMap<>();
params.put("offer", offer);
params.put("sid", sid);
params.put("uid", uid);
rpcMsg.setParams(params);
try {
String rpcText = objectMapper.writeValueAsString(rpcMsg);
webSocket.send(rpcText); // here the client sends a text message to the server, then immediately it has to wait to receive a response from the server
// should I use Thread.sleep(n), or something?
} catch (JsonProcessingException e) {
e.printStackTrace();
}
// here I need to return whatever server responses when I send the text above.
}
【问题讨论】:
-
曾经设置过超时吗?
-
什么意思?你能回答我的问题然后我可以接受你的回答吗?
-
'我不知道客户端应该休眠多长时间才能收到来自服务器的响应'——通常我们可以在客户端设置超时。不过,我不熟悉 java 中的套接字。你能指定你使用的是哪个 websocket 库吗?
-
我正在使用 OkHttp 库