使用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- response为null,对于request2,我得到response1。我希望websocket能够同步工作,这样,一旦我发送消息,就应该等待响应接收并继续前进!任何建议!
答案 0 :(得分:6)
在对象上使用wait
和notify
synchronized (someObject){
try {
someObject.wait();
result = responseFromServer();
} catch (InterruptedException e) {
//when the object is interrupted
}
}
并在onMessage
收到消息后通知对象
@Override
public void onMessage(String message) {
serverResponse.add(message);
synchronized(someObject) {
someObject.notify();
}
}
答案 1 :(得分:2)
您还可以使用CountDownLatch概念,如下面的链接所示:
@ClientEndpoint
public class WordgameClientEndpoint {
private static CountDownLatch latch;
private Logger logger = Logger.getLogger(this.getClass().getName());
@OnOpen
public void onOpen(Session session) {
// same as above
}
@OnMessage
public String onMessage(String message, Session session) {
// same as above
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
logger.info(String.format("Session %s close because of %s", session.getId(), closeReason));
latch.countDown();
}
public static void main(String[] args) {
latch = new CountDownLatch(1);
ClientManager client = ClientManager.createClient();
try {
client.connectToServer(WordgameClientEndpoint.class, new URI("ws://localhost:8025/websockets/game"));
latch.await();
} catch (DeploymentException | URISyntaxException | InterruptedException e) {
throw new RuntimeException(e);
}
}
}
@ClientEndpoint
public class WordgameClientEndpoint {
private static CountDownLatch latch;
private Logger logger = Logger.getLogger(this.getClass().getName());
@OnOpen
public void onOpen(Session session) {
// same as above
}
@OnMessage
public String onMessage(String message, Session session) {
// same as above
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
logger.info(String.format("Session %s close because of %s", session.getId(), closeReason));
latch.countDown();
}
public static void main(String[] args) {
latch = new CountDownLatch(1);
ClientManager client = ClientManager.createClient();
try {
client.connectToServer(WordgameClientEndpoint.class, new URI("ws://localhost:8025/websockets/game"));
latch.await();
} catch (DeploymentException | URISyntaxException | InterruptedException e) {
throw new RuntimeException(e);
}
}
}
https://blog.openshift.com/how-to-build-java-websocket-applications-using-the-jsr-356-api/