Ning: connect to websocket and wait for response

Using Ning to create and connect to Websocket follow my config,

 NettyAsyncHttpProviderConfig config = new NettyAsyncHttpProviderConfig();
 config.addProperty(NettyAsyncHttpProviderConfig.USE_BLOCKING_IO, "true");

 AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder()

 AsyncHttpClient client = new AsyncHttpClient(
                new NettyAsyncHttpProvider(;

 AsyncHttpClient.BoundRequestBuilder requestBuilder = client.prepareGet(createUri(method))
                .addHeader(HttpHeaders.Names.CONNECTION, "Upgrade")
                .addHeader(HttpHeaders.Names.UPGRADE, "WebSocket");

 websocket = requestBuilder.execute(new WebSocketUpgradeHandler.Builder()


using websocket to send a text message,

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



the listener method will add the response to the list

public void onMessage(String message) {


After sending a text message, I have a method that formats the response and stores the result

result = responseFromServer();

private String responseFromServer() {
    String response = null;
      //format the message which is added in list
    return response;


The problem is that if I don't 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 as soon as I post the message, it should wait for unitll, the response received and off you go! Any suggestions!


source to share

2 answers

Use wait

also notify

for the object,

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


and to onMessage

notify the object as soon as you receive the message,

public void onMessage(String message) {
     synchronized(someObject) {




You can also use the CountDownLatch concept as shown in the link below:

public class WordgameClientEndpoint {

    private static CountDownLatch latch;

    private Logger logger = Logger.getLogger(this.getClass().getName());

    public void onOpen(Session session) {
        // same as above

    public String onMessage(String message, Session session) {
        // same as above

    public void onClose(Session session, CloseReason closeReason) {"Session %s close because of %s", session.getId(), closeReason));

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

        } catch (DeploymentException | URISyntaxException | InterruptedException e) {
            throw new RuntimeException(e);





All Articles