【发布时间】:2022-01-06 23:08:48
【问题描述】:
Spring @ClientEndpoint websocket 客户端未检测到由于电缆拔出而导致的网络断开。我还实现了一个 ping/pong 机制。有人可以帮我解决发生了什么吗? 但是,我在重新连接电缆后看到以下异常,仅供参考,所有设置均为默认设置。此外,我正在连接到没有任何控制权的第 3 方远程端点。
xxxxxException: closed with code : CLOSED_ABNORMALLY reason: CloseReason: code [1006], reason [java.io.IOException: Connection reset by peer]
at xxxxxx.onClose(WSClient.java:xx)
@ClientEndpoint
public class WSClient {
private Session session;
private int i = 0;
@OnOpen
public void open(Session session) {
System.out.println("Connected to the server");
this.session = session;
}
@OnClose
public void close(Session session, CloseReason closeReason) {
System.out.println("connection closed " + closeReason.getReasonPhrase());
}
@OnError
public void error(Session session, Throwable t) {
System.out.println(session.getId());
System.out.println("Error in connection " + t.getMessage());
}
@OnMessage
public void message(Session session, String message) {
System.out.println("message received: " + message + " " + i++);
}
public void send(String message){
try {
if(session.isOpen()) {
this.session.getBasicRemote().sendPing(ByteBuffer.wrap(message.getBytes()));
System.out.println("socket is open " + i++);
} else {
System.out.println("socket closed");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Component
public class ClientApp implements ApplicationListener<ApplicationReadyEvent> {
private void startConnection() throws Exception {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
WSClient client = new WSClient();
container.connectToServer(client, new URI("ws://wshost:8080/ping"));
while (true) {
client.send("ping");
TimeUnit.SECONDS.sleep(3);
}
}
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
try {
startConnection();
} catch (Exception e) {
System.out.println(e);
}
}
}
【问题讨论】:
标签: spring spring-boot spring-websocket java-websocket