我正在尝试为Websocket构建一个客户端" wss://echo.websocket.org"。代码使用Spring 5和ReactorNettyWebSocketClient()。
public class WsClient {
public static void main(String[] args) throws InterruptedException {
WebSocketClient client = new ReactorNettyWebSocketClient();
client.execute(URI.create("wss://echo.websocket.org"),
new ClientWebSocketHandler()).block(Duration.ofSeconds(15));
System.out.println("End");
}
static class ClientWebSocketHandler implements WebSocketHandler {
@Override
public Mono<Void> handle(WebSocketSession session) {
WebSocketMessage textMessage = session.textMessage("{\"event\":\"ping\"}");
session.send(Mono.just(textMessage));
String payloadAsText = session.receive().blockFirst().getPayloadAsText();
System.out.println(payloadAsText);
return Mono.empty();
}
}
}
代码在15秒后超时。它应该发送ping消息,我希望ping消息回来。
答案 0 :(得分:1)
我找到了解决方案:
public class WsClient {
public static void main(String[] args) throws InterruptedException {
WebSocketClient client = new ReactorNettyWebSocketClient();
client.execute(URI.create("wss://echo.websocket.org"),
session -> session.send(Mono.just(
session.textMessage("{\"event\":\"ping\"}")))
.thenMany(session
.receive()
.map(WebSocketMessage::getPayloadAsText)
.log())
.then()).block(Duration.ofSeconds(10));
System.out.println("End");
}
}