javawebsockettyrus

How to make websocket synchronous


I have implemented a websocket client program using tyrus referring this example. There it was implemented in a assynchronous way. Now I want make it synchronous so that once I send a request, program will wait till the response received. Is it possible with tyrus framework? If so, how cam I do it? Below is my implementation of client program

@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);
        }
    }
}


Solution

  • There is no such thing as "synchronous websocket" as it's a whole different messaging protocol than HTTP. While HTTP is a request-response protocol, where you expect a response from the client once you sent the request, WebSocket establishes a connection using a 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.