如何使websocket同步

Posted

技术标签:

【中文标题】如何使websocket同步【英文标题】:How to make websocket synchronous 【发布时间】:2020-06-09 05:58:24 【问题描述】:

我已经使用 tyrus 实现了一个 websocket 客户端程序,引用 this 示例。它在那里以异步方式实现。现在我想让它同步,这样一旦我发送请求,程序就会等到收到响应。 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);
        
    


【问题讨论】:

NO WAY... "使用此 API,您可以向服务器发送消息并接收事件驱动的响应,而无需轮询服务器以获取回复。" MDN web docs 【参考方案1】:

没有“同步 websocket”这样的东西,因为它是一个与 HTTP 完全不同的消息传递协议。虽然 HTTP 是一种请求-响应协议,一旦您发送请求,您就希望客户端得到响应,而 WebSocket 使用handshake request 建立连接,之后通信变为双向,没有响应请求的概念。您可以在Wikipedia 阅读更多相关信息。

【讨论】:

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

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

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

如何使实时服务器 Ratchet WebSockets 工作?

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

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

如何使我的 websockets 客户端在代理服务器方面健壮?