Browse Source

前端ws测试代码

master
白凤吉 6 months ago
parent
commit
6ba346097a
  1. 79
      demo/ws_demo.html

79
demo/ws_demo.html

@ -0,0 +1,79 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket with STOMP</title>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.5.1/dist/sockjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
</head>
<body>
<h2>WebSocket STOMP Client</h2>
<input type="text" id="messageInput" placeholder="Enter your message">
<button onclick="sendMessage()">Send</button>
<div id="response"></div>
<script>
let stompClient = null;
let socket = null;
const wsUrl = 'http://localhost:8080/ws'; // WebSocket 服务器地址
const reconnectInterval = 5000; // 重连间隔(5秒)
function connectWebSocket() {
console.log("尝试连接 WebSocket...");
socket = new SockJS(wsUrl);
stompClient = Stomp.over(socket);
stompClient.debug = null; // 关闭调试日志
stompClient.connect({}, function (frame) {
console.log('WebSocket 连接成功:', frame);
// 订阅服务器的推送消息
stompClient.subscribe('/topic/greetings', function (greeting) {
const response = document.getElementById('response');
response.innerHTML = 'Server says: ' + greeting.body;
});
stompClient.subscribe('/topic/cmd', function (result) {
console.log("命令执行反馈:", result.body);
});
}, function (error) {
console.error("WebSocket 连接失败:", error);
attemptReconnect();
});
// 监听 WebSocket 关闭事件,自动重连
socket.onclose = function () {
console.warn("WebSocket 连接已断开!");
attemptReconnect();
};
}
// **重连机制**
function attemptReconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
console.log(`将在 ${reconnectInterval / 1000} 秒后尝试重新连接 WebSocket...`);
setTimeout(connectWebSocket, reconnectInterval);
}
// **发送消息**
function sendMessage() {
if (stompClient && stompClient.connected) {
const messageInput = document.getElementById('messageInput');
const message = messageInput.value;
stompClient.send("/app/hello", {}, message); // 发送消息到 "/app/hello"
console.log("消息已发送:", message);
} else {
console.warn("WebSocket 未连接,无法发送消息!");
}
}
// **初始化 WebSocket 连接**
connectWebSocket();
</script>
</body>
</html>
Loading…
Cancel
Save