1 Star 0 Fork 0

zlsxz/socket

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
index.html 1.86 KB
一键复制 编辑 原始数据 按行查看 历史
zlsxz 提交于 2024-09-13 23:59 . socket连接websocket
<!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>
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zlsxz/socket.git
[email protected]:zlsxz/socket.git
zlsxz
socket
socket
master

搜索帮助