72 lines
1.9 KiB
HTML
72 lines
1.9 KiB
HTML
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>WebSocket测试</title>
|
|
<meta charset="UTF-8">
|
|
</head>
|
|
<body>
|
|
<h2>WebSocket连接测试</h2>
|
|
<div id="output"></div>
|
|
<button onclick="sendPing()">发送Ping</button>
|
|
<button onclick="sendSubscribe()">发送Subscribe</button>
|
|
<button onclick="disconnect()">断开连接</button>
|
|
|
|
<script>
|
|
let ws = null;
|
|
const output = document.getElementById('output');
|
|
|
|
function log(message) {
|
|
output.innerHTML += '<div>' + new Date().toLocaleTimeString() + ': ' + message + '</div>';
|
|
}
|
|
|
|
function connect() {
|
|
ws = new WebSocket('ws://localhost:8080/collision');
|
|
|
|
ws.onopen = function(event) {
|
|
log('✅ WebSocket连接已建立');
|
|
};
|
|
|
|
ws.onmessage = function(event) {
|
|
log('📨 收到消息: ' + event.data);
|
|
};
|
|
|
|
ws.onclose = function(event) {
|
|
log('🔌 WebSocket连接已关闭, 代码: ' + event.code);
|
|
};
|
|
|
|
ws.onerror = function(error) {
|
|
log('❌ WebSocket错误: ' + error);
|
|
};
|
|
}
|
|
|
|
function sendPing() {
|
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
ws.send('ping');
|
|
log('➡️ 发送: ping');
|
|
} else {
|
|
log('❌ WebSocket未连接');
|
|
}
|
|
}
|
|
|
|
function sendSubscribe() {
|
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
ws.send('subscribe');
|
|
log('➡️ 发送: subscribe');
|
|
} else {
|
|
log('❌ WebSocket未连接');
|
|
}
|
|
}
|
|
|
|
function disconnect() {
|
|
if (ws) {
|
|
ws.close();
|
|
}
|
|
}
|
|
|
|
// 页面加载时自动连接
|
|
window.onload = function() {
|
|
connect();
|
|
};
|
|
</script>
|
|
</body>
|
|
</html> |