使用 Ning 创建并连接到 Websocket,以下是我的配置,
NettyAsyncHttpProviderConfig config = new NettyAsyncHttpProviderConfig();
config.addProperty(NettyAsyncHttpProviderConfig.USE_BLOCKING_IO, "true");
AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder()
.setAsyncHttpClientProviderConfig(config);
AsyncHttpClient client = new AsyncHttpClient(
new NettyAsyncHttpProvider(builder.build()));
AsyncHttpClient.BoundRequestBuilder requestBuilder = client.prepareGet(createUri(method))
.addHeader(HttpHeaders.Names.CONNECTION, "Upgrade")
.addHeader(HttpHeaders.Names.UPGRADE, "WebSocket");
websocket = requestBuilder.execute(new WebSocketUpgradeHandler.Builder()
.addWebSocketListener(this).build()).get();
使用 websocket 发送短信,
if (websocket!=null && websocket.isOpen())
websocket.sendTextMessage(jObj.toString());// send
onMessage()
侦听器的方法会将响应添加到列表中
@Override
public void onMessage(String message) {
serverResponse.add(message);
}
发送短信后,我有格式化响应并保存结果的方法
result = responseFromServer();
private String responseFromServer() {
String response = null;
sleep(100);
if(!serverResponse.isEmpty())
//format the message which is added in list
return response;
}
问题是,如果我在上述方法中没有'sleep(100)',对于request1-响应为空,对于request2,我得到response1。我希望 websocket 能够同步工作,这样,一旦我发送消息,它应该等待单元格接收到响应并继续前进!有什么建议么!