Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ning: Connect to websocket and wait for response

Using Ning to create and connect to Websocket, following is my configuration ,

 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();

using websocket to send text message,

 if (websocket!=null && websocket.isOpen())
       websocket.sendTextMessage(jObj.toString());// send

onMessage() method of the listener will add the response to a list

@Override
public void onMessage(String message) {
   serverResponse.add(message);
}

After sending the text message, I have method which formats the response and save the result

result = responseFromServer();

private String responseFromServer() {
    String response = null;
    sleep(100);
   if(!serverResponse.isEmpty())
      //format the message which is added in list
    return response;
}

issue is, if I dont have 'sleep(100)' in the above method, for request1- response is null and for request2, I get response1. I would like the websocket to work as synchronous so that, once I send the message, it should wait unitll the response is received and go forward! ANy suggestions!

like image 868
user1609085 Avatar asked Jan 10 '23 17:01

user1609085


1 Answers

Use wait and notify on a object,

synchronized (someObject){
  try {
     someObject.wait();
     result = responseFromServer();
   } catch (InterruptedException e) {
        //when the object is interrupted
   }
}

and in onMessage notify the object once you got the message,

@Override
public void onMessage(String message) {
     serverResponse.add(message);
     synchronized(someObject) {
          someObject.notify();
     }
}
like image 108
sssV Avatar answered Jan 24 '23 23:01

sssV