websocket 的ping-pong心跳

今天和unity争论websocktping-pong心跳问题,他那边说websockt要在普通message里面发送ping这个字符串给服务端,让服务端回复pong字符串。其实不是这样的,websocket协议已经定义了ping-pong的操作码。协议链接:https://www.rfc-editor.org/rfc/rfc6455
我继续继续在java中使用websocket客户端代码测试了一下ping-pong的操作码。测试代码如下:

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.PingMessage;
import org.springframework.web.socket.PongMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.net.URI;

@Component
public class WebSocketClient {

    private static final URI WS_URI = URI.create("wss://you ip port/ws");
    private WebSocketConnectionManager connectionManager;

    static WebSocketSession connectionedSession;

    public WebSocketClient() {
        StandardWebSocketClient webSocketClient = new StandardWebSocketClient();
        WebSocketHandler handler = new MyWebSocketHandler();
        this.connectionManager = new WebSocketConnectionManager(webSocketClient, handler, WS_URI);
        this.connectionManager.start();
       /* this.connectionManager.setWebSocketFactory(webSocketClient);
        this.connectionManager.setReconnectAutomatically(true);*/
    }

    private static class MyWebSocketHandler extends AbstractWebSocketHandler {
        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            connectionedSession = session;
            System.out.println("WebSocket connected");
        }

        @Override
        protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
            System.out.println("handlePongMessage ");
        }
    }

    @Scheduled(cron = "0/5 * * * * ? ") // 间隔5秒执行
    public void sendPing() {
        if (connectionedSession == null) {
            System.err.println("WebSocket session is null, cannot send ping");
            return;
        }
        try {
            connectionedSession.sendMessage(new PingMessage());
            System.out.println("Ping sent");
        } catch (Exception e) {
            System.err.println("Failed to send ping: " + e.getMessage());
        }
    }


}


要注意,定时任务生效,要在启动类上面加@EnableScheduling
其实就是发送一个0x9操作码的 ping 信息。至于其他JS端,unity端只需查资料找对应发送0x9操作码的API就行了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章