我参考了这个例子,使用tyrus实现了一个websocket客户端程序。在那里,它以异步方式实现。现在我想让它同步,这样一旦我发送请求,程序就会等到收到响应。使用tyrus框架可能吗?如果是这样,我该怎么做?以下是我对客户端程序的实现
@ClientEndpoint
public class WebSocketConnection extends Thread{
private static final Logger logger = LogManager.getLogger("WebSocketConnection");
private static CountDownLatch countDownLatch;
private boolean isClientAuthenticated = false;
private boolean isConnected = false;
private Session serverSession = null;
private boolean isTimerEnable = false;
private int i_TimeOut = 0;
private ArrayList<String> list_RTRequests;
private static final String PULSE = "Pulse message";
private static final String AUTH_REQ = "Authentication"; //I can't provide real values of these 2 variables. Hope it will not be a problem
public WebSocketConnection(boolean _isTimerEnable, int _iTimeOut, ArrayList<String> _listRTRequests) {
this.isTimerEnable = _isTimerEnable;
this.i_TimeOut = _iTimeOut;
this.list_RTRequests = _listRTRequests;
}
@Override
public void run() {
while (true) {
if (isConnected) {
if (isClientAuthenticated) {
sendPulseToClient();
sendRTs();
}
} else {
countDownLatch = new CountDownLatch(1);
ClientManager clientManager = ClientManager.createClient();
try {
clientManager.connectToServer(WebSocketConnection.class, new URI("uri"));
countDownLatch.await();
} catch (InterruptedException | URISyntaxException | DeploymentException e) {
e.printStackTrace();
}
}
try {
sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@OnOpen
public void onOpen(Session session){
System.out.println("Connected... " + session.getId());
isConnected = true;
try {
logger.info("AUTH_REQ Sent : "+ AUTH_REQ);
session.getBasicRemote().sendText(AUTH_REQ);
serverSession = session;
} catch (IOException e) {
logger.error("Authentication Error : " + e);
}
}
@OnMessage
public String onMessage(String _sMessage, Session session){
//System.out.println("Response : " +_sMessage);
logger.info("Response : " +_sMessage);
return _sMessage;
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println("Session " +session.getId()+" close because of "+ closeReason);
countDownLatch.countDown();
isConnected = false;
logger.info(String.format("Session %s close because of %s", session.getId(), closeReason));
}
private void sendPulseToClient() {
try {
serverSession.getBasicRemote().sendText(PULSE);
System.out.println("send pulse : " + PULSE);
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendRTs(){
try {
if(! list_RTRequests.isEmpty()){
for(String rt : list_RTRequests){
if (isTimerEnable){
serverSession.getBasicRemote().sendText(rt);
sleep(i_TimeOut);
} else {
serverSession.getBasicRemote().sendText(rt);
countDownLatch.await();
}
}
}
} catch (IOException | InterruptedException e) {
logger.error("Error sending request : " + e);
}
}
}
没有"同步websocket"这样的东西,因为它与HTTP完全不同。虽然 HTTP 是一种请求-响应协议,您希望在发送请求后得到客户端的响应,但 WebSocket 使用握手请求建立连接,之后通信将变为双向,其中没有响应请求的概念。您可以在维基百科中阅读更多相关信息。