为了实现优雅重连和重试,您需要在代码中添加一些逻辑来处理连接失败或断开连接的情况。
实现代码如下:
java
import javax.websocket.*;
import java.io.IOException;
@ClientEndpoint
public class WebSocketClientEndpoint {
private Session userSession = null;
private MessageHandler messageHandler;
private int retryCount = 0;
public WebSocketClientEndpoint(String endpointURI) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, URI.create(endpointURI));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@OnOpen
public void onOpen(Session userSession) {
System.out.println("opening websocket");
this.userSession = userSession;
}
@OnClose
public void onClose(Session userSession, CloseReason reason) {
System.out.println("closing websocket");
this.userSession = null;
retryConnect();
}
@OnMessage
public void onMessage(String message) {
if (this.messageHandler != null) {
this.messageHandler.handleMessage(message);
}
}
@OnOpenException
public void onOpenException(Exception ex) {
System.out.println("Error opening websocket: " + ex.getMessage());
retryConnect();
}
private void retryConnect() {
if (retryCount < 5) {
try {
Thread.sleep(1000); // 等待1秒后重试连接
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, URI.create("ws://localhost:8080/my-websocket-endpoint"));
retryCount++;
} catch (Exception e) {
System.out.println("Error reconnecting: " + e.getMessage());
retryConnect(); // 如果连接失败,继续重试连接
}
} else {
System.out.println("Max retries reached, giving up.");
}
}
public void sendMessage(String message) throws IOException {
this.userSession.getBasicRemote().sendText(message);
}
public void addMessageHandler(MessageHandler handler) {
this.messageHandler = handler;
}
}