【发布时间】:2019-06-11 21:45:43
【问题描述】:
我在 java 中有一个简单的 WebSocket 客户端。有时与 WebSocket 服务器的连接可能会丢失。如果连接丢失如何自动重新连接?
import javax.websocket.*;
import java.net.URI;
@ClientEndpoint
public class WebsocketClientEndpoint {
Session userSession = null;
public WebsocketClientEndpoint(URI endpointURI) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, 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;
}
@OnMessage
public void onMessage(String message) {
System.out.println("Received message: "+ message);
}
public void sendMessage(String message) {
this.userSession.getAsyncRemote().sendText(message);
}
}
测试应用
import java.net.URI;
import java.net.URISyntaxException;
public class TestApp {
public static void main(String[] args) {
try {
final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(new URI("ws://localhost:8080/websocket/api"));
while (true) {
Thread.sleep(30000);
}
} catch (Exception ex) {
System.err.println("Exception: " + ex.getMessage());
}
}
}
java中有简单的WebSocket客户端和测试类。有时与 WebSocket 服务器的连接可能会丢失。如果连接丢失如何自动重新连接?
【问题讨论】: