生成一个完美并能查看以前的所有的聊天记录的网页聊天实例并给予一个服务端与客户端
在下面给出了一个简单的网页聊天实例,其中包括了服务端和客户端的代码。这个聊天实例使用WebSocket来实现实时的双向通信,并将聊天记录存储在服务端,以便以后查看。
服务端代码(Node.js):
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const messages = [];
wss.on('connection', (ws) => {
// 发送已有的聊天记录给新加入的客户端
ws.send(JSON.stringify(messages));
// 接收客户端发来的消息
ws.on('message', (message) => {
const data = JSON.parse(message);
messages.push(data);
// 将消息广播给所有连接的客户端
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data));
}
});
});
});
server.listen(3000, () => {
console.log('Server started on port 3000');
});
客户端代码(HTML + JavaScript):
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
<style>
#chat-box {
width: 400px;
height: 300px;
border: 1px solid #ccc;
overflow-y: scroll;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div id="chat-box"></div>
<input type="text" id="message-input" placeholder="Type a message">
<button id="send-button">Send</button>
<script>
const chatBox = document.getElementById('chat-box');
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-button');
const socket = new WebSocket('ws://localhost:3000');
// 接收服务端发送的消息
socket.onmessage = (event) => {
const message = JSON.parse(event.data);
displayMessage(message);
};
// 发送消息给服务端
sendButton.addEventListener('click', () => {
const message = messageInput.value;
if (message.trim() !== '') {
const data = {
sender: 'client',
text: message,
timestamp: new Date().toLocaleString()
};
socket.send(JSON.stringify(data));
displayMessage(data);
messageInput.value = '';
}
});
// 显示消息在聊天窗口
function displayMessage(message) {
const messageElement = document.createElement('p');
messageElement.textContent = `[${message.timestamp}] ${message.sender}: ${message.text}`;
chatBox.appendChild(messageElement);
chatBox.scrollTop = chatBox.scrollHeight;
}
</script>
</body>
</html>
使用这个聊天实例,你需要先安装Node.js和WebSocket库(通过运行npm install express http ws命令)。然后,将服务端代码保存为server.js文件,运行node server.js启动服务端。最后,将客户端代码保存为client.html文件,使用浏览器打开它,即可开始聊天。
聊天记录会在内存中保存,如果需要持久化存储,可以将数据存储到数据库或者文件中。同时,可以根据需求添加更多功能,如用户认证、私聊、表情符号等
原文地址: https://www.cveoy.top/t/topic/iLIf 著作权归作者所有。请勿转载和采集!