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