在网页开发中,实时聊天窗口是提升用户交互体验的重要功能,借助HTML搭建界面结构,配合WebSocket实现双向实时通信,就能完成完整的聊天功能开发。下面我们就一步步实现这个功能。

一、聊天界面基础结构搭建
首先我们需要用HTML构建聊天窗口的基本布局,包含消息展示区域、输入框和发送按钮三个核心部分。这里使用语义化的标签来组织内容,方便后续样式调整和功能扩展。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>实时聊天窗口</title>
<style>
.chat-container {
width: 400px;
height: 600px;
border: 1px solid #ccc;
margin: 20px auto;
display: flex;
flex-direction: column;
}
.message-area {
flex: 1;
padding: 10px;
overflow-y: auto;
border-bottom: 1px solid #ccc;
}
.input-area {
display: flex;
padding: 10px;
}
#messageInput {
flex: 1;
margin-right: 10px;
padding: 5px;
}
.message-item {
margin: 5px 0;
padding: 5px 10px;
border-radius: 5px;
max-width: 70%;
}
.self-message {
background-color: #95ec69;
margin-left: auto;
}
.other-message {
background-color: #f0f0f0;
margin-right: auto;
}
</style>
</head>
<body>
<div class="chat-container">
<div class="message-area" id="messageArea"></div>
<div class="input-area">
<input type="text" id="messageInput" placeholder="请输入聊天内容">
<button id="sendBtn">发送</button>
</div>
</div>
</body>
</html>
二、WebSocket连接建立
WebSocket可以实现客户端和服务端的双向实时通信,不需要像HTTP请求那样反复建立连接。我们首先在前端代码中创建WebSocket实例,连接到后端提供的WebSocket服务地址。
这里需要注意,如果后端服务运行在本地,地址可以使用ws://127.0.0.1:8080/chat这样的格式,实际部署时替换为对应的正式地址即可。
// 创建WebSocket连接,本地服务地址示例
const socket = new WebSocket('ws://127.0.0.1:8080/chat');
// 连接成功时的回调
socket.onopen = function() {
console.log('WebSocket连接已建立');
};
// 接收服务端消息的回调
socket.onmessage = function(event) {
const messageData = JSON.parse(event.data);
displayMessage(messageData.content, 'other');
};
// 连接关闭时的回调
socket.onclose = function() {
console.log('WebSocket连接已关闭');
};
// 连接出错时的回调
socket.onerror = function(error) {
console.error('WebSocket连接出错:', error);
};
三、消息收发逻辑实现
接下来需要实现两个核心功能:一是点击发送按钮或者按下回车键时,把输入框的内容通过WebSocket发送给服务端;二是把收到的消息和发送的消息都展示在消息区域中。
// 获取页面元素
const messageArea = document.getElementById('messageArea');
const messageInput = document.getElementById('messageInput');
const sendBtn = document.getElementById('sendBtn');
// 展示消息的函数
function displayMessage(content, type) {
const messageItem = document.createElement('div');
messageItem.className = `message-item ${type === 'self' ? 'self-message' : 'other-message'}`;
messageItem.textContent = content;
messageArea.appendChild(messageItem);
// 滚动到消息区域底部
messageArea.scrollTop = messageArea.scrollHeight;
}
// 发送消息的函数
function sendMessage() {
const content = messageInput.value.trim();
if (!content) {
return;
}
// 展示自己发送的消息
displayMessage(content, 'self');
// 通过WebSocket发送消息给服务端
const messageObj = {
type: 'chat',
content: content
};
socket.send(JSON.stringify(messageObj));
// 清空输入框
messageInput.value = '';
}
// 绑定发送按钮点击事件
sendBtn.addEventListener('click', sendMessage);
// 绑定输入框回车键发送事件
messageInput.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
sendMessage();
}
});
四、后端简单示例参考
前端功能完成后,还需要对应的后端服务来处理WebSocket连接和消息转发。这里提供一个Node.js的简单后端示例,帮助理解整体通信流程。
const WebSocket = require('ws');
// 创建WebSocket服务,端口8080
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
console.log('有新的客户端连接');
// 接收客户端发送的消息
ws.on('message', function incoming(message) {
console.log('收到消息:', message);
// 把消息广播给所有连接的客户端
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
// 连接关闭时的处理
ws.on('close', function() {
console.log('客户端连接已关闭');
});
});
console.log('WebSocket服务运行在 ws://127.0.0.1:8080');
五、注意事项
- 实际开发中需要对消息内容做合法性校验,避免XSS攻击,不要直接把用户输入的内容不做处理就插入到DOM中。
- WebSocket连接可能会因为网络问题断开,需要添加重连机制,保证聊天功能的稳定性。
- 如果需要实现私聊、消息存储等功能,需要后端配合做更多的逻辑处理,比如用户身份识别、消息持久化等。