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就行了。

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