mirror of
https://github.com/JeffLi1993/springboot-learning-example.git
synced 2026-03-13 21:43:45 +08:00
WebFlux 中 WebSocket 实现通信
This commit is contained in:
@@ -12,6 +12,7 @@ public class EchoHandler implements WebSocketHandler {
|
||||
public Mono<Void> handle(final WebSocketSession session) {
|
||||
return session.send(
|
||||
session.receive()
|
||||
.map(msg -> session.textMessage("服务端返回:小明, -> " + msg.getPayloadAsText())));
|
||||
.map(msg -> session.textMessage(
|
||||
"服务端返回:小明, " + msg.getPayloadAsText())));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,22 +6,24 @@
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="events"></div>
|
||||
<div class="chat"></div>
|
||||
|
||||
<script>
|
||||
var clientWebSocket = new WebSocket("ws://localhost:8080/echo");
|
||||
|
||||
clientWebSocket.onopen = function () {
|
||||
console.log("clientWebSocket.onopen", clientWebSocket);
|
||||
console.log("clientWebSocket.readyState", "websocketstatus");
|
||||
clientWebSocket.send("你好");
|
||||
clientWebSocket.send("你好!");
|
||||
}
|
||||
|
||||
clientWebSocket.onclose = function (error) {
|
||||
console.log("clientWebSocket.onclose", clientWebSocket, error);
|
||||
events("再见");
|
||||
events("聊天会话关闭!");
|
||||
}
|
||||
|
||||
function events(responseEvent) {
|
||||
document.querySelector(".events").innerHTML += responseEvent + "<br>";
|
||||
document.querySelector(".chat").innerHTML += responseEvent + "<br>";
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -7,6 +7,8 @@ import java.net.URI;
|
||||
import java.time.Duration;
|
||||
|
||||
public class WSClient {
|
||||
|
||||
|
||||
public static void main(final String[] args) {
|
||||
final WebSocketClient client = new ReactorNettyWebSocketClient();
|
||||
client.execute(URI.create("ws://localhost:8080/echo"), session ->
|
||||
|
||||
Reference in New Issue
Block a user