106 lines
3.4 KiB
HTML
106 lines
3.4 KiB
HTML
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>Chat Test</title>
|
|
<style>
|
|
#messages { height: 300px; overflow-y: auto; border: 1px solid #ccc; padding: 10px; margin: 10px 0; }
|
|
input[type=text] { width: 70%; padding: 5px; }
|
|
button { padding: 5px 10px; margin: 5px; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<h2>多人聊天测试</h2>
|
|
|
|
<div>
|
|
<label>用户名: <input id="username" value="alice"></label>
|
|
<button onclick="connect()">连接</button>
|
|
</div>
|
|
|
|
<div id="messages"></div>
|
|
|
|
<div>
|
|
<input type="text" id="globalMsg" placeholder="全体消息...">
|
|
<button onclick="sendGlobal()">发送全体</button>
|
|
</div>
|
|
|
|
<div>
|
|
<input type="text" id="roomID" value="game" placeholder="房间ID">
|
|
<input type="text" id="roomMsg" placeholder="房间消息...">
|
|
<button onclick="sendRoom()">发送房间</button>
|
|
</div>
|
|
|
|
<div>
|
|
<input type="text" id="toUser" value="bob" placeholder="私聊对象">
|
|
<input type="text" id="privateMsg" placeholder="私聊内容...">
|
|
<button onclick="sendPrivate()">发送私聊</button>
|
|
</div>
|
|
|
|
<script>
|
|
let ws;
|
|
|
|
function connect() {
|
|
const user = document.getElementById('username').value;
|
|
if (!user) { alert('请输入用户名'); return; }
|
|
|
|
if (ws) ws.close();
|
|
|
|
ws = new WebSocket(`ws://localhost:8080/ws?user=${user}`);
|
|
|
|
ws.onopen = () => log('🟢 连接成功');
|
|
ws.onclose = () => log('🔴 连接断开');
|
|
ws.onerror = (err) => log('❌ 连接错误: ' + err.message);
|
|
|
|
ws.onmessage = (event) => {
|
|
try {
|
|
const msg = JSON.parse(event.data);
|
|
log(`[${msg.type}] ${msg.user || 'system'}: ${msg.content}`);
|
|
} catch (e) {
|
|
log('⚠️ 无效消息: ' + event.data);
|
|
}
|
|
};
|
|
}
|
|
|
|
function sendGlobal() {
|
|
const content = document.getElementById('globalMsg').value;
|
|
if (!content) return;
|
|
ws.send(JSON.stringify({
|
|
type: 'broadcast',
|
|
user: '',
|
|
content: content
|
|
}));
|
|
document.getElementById('globalMsg').value = '';
|
|
}
|
|
|
|
function sendRoom() {
|
|
const room = document.getElementById('roomID').value;
|
|
const content = document.getElementById('roomMsg').value;
|
|
if (!room || !content) return;
|
|
ws.send(JSON.stringify({
|
|
type: 'room',
|
|
room: room,
|
|
content: content
|
|
}));
|
|
document.getElementById('roomMsg').value = '';
|
|
}
|
|
|
|
function sendPrivate() {
|
|
const to = document.getElementById('toUser').value;
|
|
const content = document.getElementById('privateMsg').value;
|
|
if (!to || !content) return;
|
|
ws.send(JSON.stringify({
|
|
type: 'private',
|
|
to: to,
|
|
content: content
|
|
}));
|
|
document.getElementById('privateMsg').value = '';
|
|
}
|
|
|
|
function log(msg) {
|
|
const div = document.createElement('div');
|
|
div.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
|
|
document.getElementById('messages').appendChild(div);
|
|
div.scrollIntoView();
|
|
}
|
|
</script>
|
|
</body>
|
|
</html> |