java websocket心跳检测代码
时间: 2023-07-08 10:07:04 浏览: 122
以下是一个简单的Java WebSocket心跳检测代码示例,可以通过发送Ping消息并等待Pong响应来检测WebSocket连接是否仍然处于活动状态:
```
import java.net.URI;
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;
@OnOpen
public void onOpen(Session session) {
this.session = session;
System.out.println("WebSocket opened: " + session.getId());
sendPing();
}
@OnMessage
public void onMessage(String message) {
if ("pong".equals(message)) {
System.out.println("Received Pong: " + message);
sendPing();
} else {
System.out.println("Received Message: " + message);
}
}
@OnError
public void onError(Throwable t) {
System.err.println("WebSocket error: " + t.getMessage());
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println("WebSocket closed with reason: " + closeReason.getReasonPhrase());
}
private void sendPing() {
try {
session.getBasicRemote().sendText("ping");
System.out.println("Sent Ping: " + session.getId());
Thread.sleep(5000); // Wait for Pong response
} catch (Exception e) {
System.err.println("Failed to send Ping: " + e.getMessage());
}
}
public static void main(String[] args) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
URI uri = new URI("ws://localhost:8080/endpoint");
container.connectToServer(WebSocketClient.class, uri);
} catch (Exception e) {
System.err.println("Failed to connect to WebSocket server: " + e.getMessage());
}
}
}
```
在上面的代码中,onOpen()方法在WebSocket连接打开时发送第一个Ping消息。onMessage()方法接收来自服务器的消息,并根据接收到的消息类型进行处理。如果收到Pong响应,则发送另一个Ping消息。如果收到其他类型的消息,则将其打印到控制台上。
sendPing()方法使用session.getBasicRemote().sendText()发送Ping消息,并等待5000毫秒以等待Pong响应。如果在等待期间未收到Pong响应,则会捕获InterruptedException异常,并将错误消息打印到控制台上。
最后,在main()方法中,我们使用WebSocketContainer.connectToServer()方法连接到WebSocket服务器并启动客户端。请注意,URI参数应该是WebSocket服务器的端点地址。
阅读全文