Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I created a web socket client using this lib

https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/example/ExampleClient.java

Could you tell me how can I stop the main thread and recaive a proper serverResponse value?

My code:

Java
class MySocketClient extends WebSocketClient {

String serverResponse;

public void onMessage( String message ) {


             serverResponse = message; 
		
	}
}

class A {

public String f () {


   MySocketClient c = new MySocketClient( new URI(...));
   c.connect();

   c.send("request");

  return c.serverResponse;  // I see null here because this line is executed before the line from onMessage method
   
}
}


What I have tried:

I tried to use semaphore It is working but It is a good practice to solve the problem this way ?
Posted
Updated 18-Apr-20 4:58am
v3
Comments
[no name] 18-Apr-20 9:47am    
Not clear, at least for me
"when I tried to use release inside other method and call that method inside onMessage...":
Which method you mean here "call that method inside"?

Btw: For me it is how things work. You receive the answer in onMessage.
Member 13702159 18-Apr-20 11:00am    
I have written my problem more clearly.
"serverResponse" is null when I return this in "f" method, I expect the value from "message" variable.

[no name] 18-Apr-20 11:09am    
Yes that is not uncommon that the response in "f" method is null becuase you have to pay attention that it needs some time to receive the answer from the server.

Your approach (which you unfortunately deleted) with semaphore is the right direction. I don't know java so I'm not sure wheter Semaphore is the right/efficient way, in Windows e.g. I would use Events, but the way you went with semaphore ends in the same result.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900