如何使Websocket同步

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使Websocket同步相关的知识,希望对你有一定的参考价值。

我参考this示例使用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);
        }
    }
}

答案

没有“同步网络套接字”之类的东西,因为它是与HTTP完全不同的消息传递协议。虽然HTTP是一种请求-响应协议,但是您希望在发送请求后得到客户端的响应,而WebSocket使用handshake request建立连接,此后通信就变成双向通信,其中没有响应请求的概念。您可以在Wikipedia中了解更多信息。

以上是关于如何使Websocket同步的主要内容,如果未能解决你的问题,请参考以下文章

如何使列表视图出现在片段中?

如何将 Django HTTP 登录会话与 Websocket 会话/Cookie 同步?

如何使 websocket 流广播到许多其他页面?

如何使 Meteor 方法同步?

如何使用 node.js 使 Websocket 服务器安全

如何使 PHP 服务器 websocket 在域上工作?