代码拉取完成,页面将自动刷新
<!DOCTYPE html>
<html lang="zh">
<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; }
#chat { border: 1px solid #ccc; height: 300px; overflow-y: scroll; padding: 10px; }
#message { width: 80%; }
#send { width: 15%; }
</style>
</head>
<body>
<h1>WebSocket 聊天室</h1>
<div id="chat"></div>
<input type="text" id="message" placeholder="输入消息..." value="1111"/>
<button id="send" disabled>发送</button>
<script>
const chat = document.getElementById('chat');
const messageInput = document.getElementById('message');
const sendButton = document.getElementById('send');
const socket = new WebSocket('ws://127.0.0.1:9696');
socket.onopen = function() {
sendButton.disabled = false; // 启用发送按钮
};
socket.onmessage = function(event) {
const msg = JSON.parse(event.data);
chat.innerHTML += '<div>' + msg + '</div>';
chat.scrollTop = chat.scrollHeight; // 滚动到最新消息
};
sendButton.onclick = function() {
const msg = messageInput.value;
if (msg) {
socket.send(msg);
messageInput.value = '';
}
};
messageInput.addEventListener('keypress', function(event) {
if (event.key === 'Enter') {
sendButton.click();
}
});
socket.onerror = function(error) {
console.error('WebSocket Error: ', error);
};
socket.onclose = function() {
sendButton.disabled = true; // 禁用发送按钮
chat.innerHTML += '<div>连接已关闭</div>';
};
</script>
</body>
</html>
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。