如何使websocket同步
How to make websocket synchronous
我已经使用 tyrus 参考 this 示例实现了一个 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);
}
}
}
没有 "synchronous websocket" 这样的东西,因为它是一种与 HTTP 完全不同的消息传递协议。 HTTP 是一种请求-响应协议,您希望在发送请求后得到客户端的响应,而 WebSocket 使用 handshake request, after which the communication becomes bidirectional where there is no concept of response to a request. You can read more about it in Wikipedia.
建立连接
我已经使用 tyrus 参考 this 示例实现了一个 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);
}
}
}
没有 "synchronous websocket" 这样的东西,因为它是一种与 HTTP 完全不同的消息传递协议。 HTTP 是一种请求-响应协议,您希望在发送请求后得到客户端的响应,而 WebSocket 使用 handshake request, after which the communication becomes bidirectional where there is no concept of response to a request. You can read more about it in Wikipedia.
建立连接