Files
happy-life-star/web/test-websocket.html
T

233 lines
8.0 KiB
HTML

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket连接测试</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.status {
padding: 10px;
margin: 10px 0;
border-radius: 5px;
}
.connected { background-color: #d4edda; color: #155724; }
.disconnected { background-color: #f8d7da; color: #721c24; }
.connecting { background-color: #fff3cd; color: #856404; }
.log {
background-color: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 5px;
padding: 10px;
height: 300px;
overflow-y: auto;
font-family: monospace;
font-size: 12px;
}
.controls {
margin: 20px 0;
}
button {
padding: 10px 20px;
margin: 5px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.btn-primary { background-color: #007bff; color: white; }
.btn-success { background-color: #28a745; color: white; }
.btn-danger { background-color: #dc3545; color: white; }
.btn-secondary { background-color: #6c757d; color: white; }
input[type="text"] {
padding: 8px;
border: 1px solid #ccc;
border-radius: 3px;
width: 300px;
}
</style>
</head>
<body>
<h1>WebSocket连接测试</h1>
<div id="status" class="status disconnected">
状态: 未连接
</div>
<div class="controls">
<button id="connectBtn" class="btn-primary" onclick="connect()">连接</button>
<button id="disconnectBtn" class="btn-danger" onclick="disconnect()" disabled>断开</button>
<button class="btn-secondary" onclick="clearLog()">清空日志</button>
</div>
<div class="controls">
<input type="text" id="messageInput" placeholder="输入测试消息..." />
<button id="sendBtn" class="btn-success" onclick="sendMessage()" disabled>发送消息</button>
</div>
<h3>连接日志:</h3>
<div id="log" class="log"></div>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.6.1/dist/sockjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
<script>
let stompClient = null;
let connected = false;
function setStatus(status, className) {
const statusEl = document.getElementById('status');
statusEl.textContent = `状态: ${status}`;
statusEl.className = `status ${className}`;
}
function log(message) {
const logEl = document.getElementById('log');
const timestamp = new Date().toLocaleTimeString();
logEl.innerHTML += `[${timestamp}] ${message}\n`;
logEl.scrollTop = logEl.scrollHeight;
}
function updateButtons() {
document.getElementById('connectBtn').disabled = connected;
document.getElementById('disconnectBtn').disabled = !connected;
document.getElementById('sendBtn').disabled = !connected;
}
function connect() {
const wsUrl = 'http://localhost:19089/ws/chat';
log(`尝试连接到: ${wsUrl}`);
setStatus('连接中...', 'connecting');
try {
const socket = new SockJS(wsUrl);
stompClient = Stomp.over(socket);
// 禁用调试日志
stompClient.debug = null;
const headers = {
'X-User-Id': `test_user_${Date.now()}`
};
stompClient.connect(headers, function(frame) {
log('WebSocket连接成功!');
log(`连接帧: ${frame}`);
setStatus('已连接', 'connected');
connected = true;
updateButtons();
// 订阅用户消息
stompClient.subscribe('/user/queue/messages', function(message) {
log(`收到用户消息: ${message.body}`);
try {
const data = JSON.parse(message.body);
log(`解析后的消息: ${JSON.stringify(data, null, 2)}`);
} catch (e) {
log(`消息解析失败: ${e.message}`);
}
});
// 订阅广播消息
stompClient.subscribe('/topic/broadcast', function(message) {
log(`收到广播消息: ${message.body}`);
});
// 发送连接消息
const connectRequest = {
userId: headers['X-User-Id'],
clientType: 'web',
clientVersion: '1.0.0',
timestamp: Date.now()
};
stompClient.send('/app/chat.connect', {}, JSON.stringify(connectRequest));
log('发送连接消息');
}, function(error) {
log(`连接失败: ${error}`);
setStatus('连接失败', 'disconnected');
connected = false;
updateButtons();
});
} catch (error) {
log(`连接异常: ${error.message}`);
setStatus('连接异常', 'disconnected');
connected = false;
updateButtons();
}
}
function disconnect() {
if (stompClient && connected) {
stompClient.disconnect(function() {
log('WebSocket连接已断开');
setStatus('已断开', 'disconnected');
connected = false;
updateButtons();
});
}
}
function sendMessage() {
const messageInput = document.getElementById('messageInput');
const content = messageInput.value.trim();
if (!content) {
alert('请输入消息内容');
return;
}
if (!stompClient || !connected) {
alert('WebSocket未连接');
return;
}
const chatRequest = {
content: content,
senderId: `test_user_${Date.now()}`,
senderType: 'USER',
messageType: 'TEXT',
timestamp: Date.now()
};
try {
stompClient.send('/app/chat.send', {}, JSON.stringify(chatRequest));
log(`发送消息: ${content}`);
messageInput.value = '';
} catch (error) {
log(`发送消息失败: ${error.message}`);
}
}
function clearLog() {
document.getElementById('log').innerHTML = '';
}
// 回车发送消息
document.getElementById('messageInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
// 页面加载完成后的初始化
window.onload = function() {
log('页面加载完成,准备测试WebSocket连接');
updateButtons();
};
// 页面卸载时断开连接
window.onbeforeunload = function() {
if (connected) {
disconnect();
}
};
</script>
</body>
</html>