java websocket心跳检测重连代码
时间: 2023-10-31 19:56:03 浏览: 248
以下是一个简单的Java WebSocket心跳检测和重连的代码示例:
```java
import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
@ClientEndpoint
public class WebSocketClient {
private Session session;
private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
@OnOpen
public void onOpen(Session session) {
System.out.println("Connected to server");
this.session = session;
startHeartbeat();
}
@OnMessage
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
@OnClose
public void onClose(CloseReason reason) {
System.out.println("Connection closed: " + reason.getReasonPhrase());
stopHeartbeat();
reconnect();
}
@OnError
public void onError(Throwable throwable) {
System.out.println("Error: " + throwable.getMessage());
stopHeartbeat();
reconnect();
}
private void startHeartbeat() {
executor.scheduleAtFixedRate(() -> {
try {
session.getBasicRemote().sendText("ping");
} catch (Exception e) {
System.out.println("Error sending heartbeat: " + e.getMessage());
}
}, 0, 30, TimeUnit.SECONDS);
}
private void stopHeartbeat() {
executor.shutdown();
}
private void reconnect() {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
container.connectToServer(this, new URI("wss://example.com"));
} catch (Exception e) {
System.out.println("Error reconnecting: " + e.getMessage());
}
}
}
```
在上面的示例中,`startHeartbeat()` 方法使用定时器每30秒向服务器发送一个心跳消息。如果发送心跳消息失败,则会在控制台记录错误消息并停止心跳定时器。
如果WebSocket连接关闭或发生错误,`onClose()` 或 `onError()` 方法将会被调用,这时代码将会停止心跳定时器并尝试重新连接。重新连接使用的是Java WebSocket API的内置功能。
你可以根据自己的需求调整心跳间隔时间和重连策略。
阅读全文