今天和unity
爭論websockt
的ping-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就行了。