使用node+socket搭建一个星铁聊天室👻👻
introduce
现代网页聊天应用是一款基于Node.js和Socket.IO的实时聊天系统,旨在为用户提供流畅且互动性强的在线聊天体验。该应用采用前后端分离的开发模式,前端使用HTML、CSS和JavaScript构建用户界面,后端使用Node.js和Socket.IO实现实时通信功能。应用支持文字、表情、图片、音频和视频等多种消息类型的发送和接收,用户可以通过头像选择器更换自己的头像,并且群主还拥有更改聊天室名称的特权。
要实现一个基于Node.js和Socket.IO的网页聊天室
- 创建一个Node.js项目。
- 安装必要的依赖库。
- 设置服务器端Socket.IO。
- 创建客户端HTML和JavaScript代码。
- 实现聊天功能,支持三个角色:阿晴、瓦尔特、三月七。
1. 创建Node.js项目
首先,初始化一个新的Node.js项目:
mkdir chat-app
cd chat-app
npm init -y
2. 安装必要的依赖库
安装Express和Socket.IO:
npm install express socket.io
3. 设置服务器端Socket.IO
创建 server.js
:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
app.use(express.static('public'));
let users = [];
let owner = null;
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
const user = users.find(u => u.id === socket.id);
if (user) {
users = users.filter(u => u.id !== socket.id);
io.emit('user left', user);
// If the owner leaves, assign a new owner if there are remaining users
if (owner && owner.id === socket.id && users.length > 0) {
owner = users[0];
owner.isOwner = true; // Update the new owner status
io.emit('new owner', owner);
}
}
});
socket.on('join chat', (nickname) => {
const avatarIndex = users.length % 25 + 1; // 1 to 25
const avatar = `avatar/100${avatarIndex < 10 ? '0' : ''}${avatarIndex}.png`;
const user = { id: socket.id, nickname, avatar, isOwner: false };
users.push(user);
if (!owner) {
owner = user;
user.isOwner = true;
}
io.emit('user joined', { user, isOwner: user.isOwner });
});
socket.on('chat message', (msg) => {
const user = users.find(u => u.id === socket.id);
if (user) {
io.emit('chat message', { user, msg });
}
});
socket.on('emoji message', (msg) => {
const user = users.find(u => u.id === socket.id);
if (user) {
io.emit('emoji message', { user, msg });
}
});
socket.on('image message', (msg) => {
const user = users.find(u => u.id === socket.id);
if (user) {
io.emit('image message', { user, msg });
}
});
socket.on('audio message', (msg) => {
const user = users.find(u => u.id === socket.id);
if (user) {
io.emit('audio message', { user, msg });
}
});
socket.on('video message', (msg) => {
const user = users.find(u => u.id === socket.id);
if (user) {
io.emit('video message', { user, msg });
}
});
socket.on('change chat name', (newName) => {
if (owner && owner.id === socket.id) {
io.emit('chat name changed', newName);
}
});
socket.on('change avatar', (avatar) => {
const user = users.find(u => u.id === socket.id);
if (user) {
user.avatar = avatar;
io.emit('avatar changed', user);
}
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
4. 创建客户端HTML和JavaScript代码
在 public
目录下创建一个 index.html
文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat Interface</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="nickname-container">
<input type="text" id="nicknameInput" placeholder="Enter your nickname">
<button id="joinButton">Join Chat</button>
</div>
<div class="chat-container" style="display: none;">
<div class="chat-header">
<span id="chatName">1111111111</span>
<input type="text" id="chatNameInput" style="display: none;">
<button id="changeChatNameButton" style="display: none;">Change</button>
</div>
<div class="chat-messages" id="messages">
<!-- Messages will be appended here -->
</div>
<div class="chat-input-container">
<button class="emoji-button">😊</button>
<input type="text" id="messageInput" placeholder="输入消息..." class="chat-input">
<button class="upload-button">+</button>
<input type="file" id="fileInput" class="file-input" accept="image/*,audio/*,video/*" style="display: none;">
<button class="send-button" id="sendButton">发送</button>
</div>
<div class="emoji-picker" id="emojiPicker" style="display: none;">
<!-- Emoji images will be dynamically appended here by JavaScript -->
</div>
</div>
<div id="avatarModal" class="modal" style="display: none;">
<div class="modal-content">
<span class="close">×</span>
<h2>Select Your Avatar</h2>
<div class="avatars">
<script>
for (let i = 1; i <= 25; i++) {
const index = i.toString().padStart(2, '0');
document.write(`<img src="avatar/100${index}.png" alt="avatar${i}" class="avatar-option">`);
}
</script>
</div>
</div>
</div>
<script src="emoji.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="script.js"></script>
</body>
</html>
5. 实现客户端JavaScript代码
创建一个 public/script.js
文件:
const socket = io();
let currentUser = null;
let isOwner = false;
document.getElementById('joinButton').addEventListener('click', () => {
const nickname = document.getElementById('nicknameInput').value.trim();
if (nickname) {
socket.emit('join chat', nickname);
currentUser = nickname;
document.getElementById('nickname-container').style.display = 'none';
document.querySelector('.chat-container').style.display = 'flex';
loadEmojis(); // Load emojis when the chat interface is displayed
}
});
socket.on('user joined', ({ user, isOwner: ownerStatus }) => {
if (user.nickname === currentUser) {
isOwner = ownerStatus;
if (isOwner) {
document.getElementById('changeChatNameButton').style.display = 'block';
}
}
appendSystemMessage(`${user.nickname} joined the chat`);
});
socket.on('user left', (user) => {
appendSystemMessage(`${user.nickname} left the chat`);
});
socket.on('chat message', ({ user, msg }) => {
appendMessage(user, msg);
});
socket.on('emoji message', ({ user, msg }) => {
appendMessage(user, msg);
});
socket.on('image message', ({ user, msg }) => {
appendImageMessage(user, msg);
});
socket.on('audio message', ({ user, msg }) => {
appendAudioMessage(user, msg);
});
socket.on('video message', ({ user, msg }) => {
appendVideoMessage(user, msg);
});
socket.on('chat name changed', (newName) => {
document.getElementById('chatName').innerText = newName;
});
socket.on('new owner', (user) => {
if (user.nickname === currentUser) {
isOwner = true;
document.getElementById('changeChatNameButton').style.display = 'block';
} else {
isOwner = false;
document.getElementById('changeChatNameButton').style.display = 'none';
}
appendSystemMessage(`${user.nickname} is the new owner`);
updateOwner(user);
});
socket.on('avatar changed', (user) => {
updateAvatar(user);
});
document.getElementById('changeChatNameButton').addEventListener('click', () => {
const chatNameInput = document.getElementById('chatNameInput');
chatNameInput.style.display = 'block';
chatNameInput.focus();
document.getElementById('chatName').style.display = 'none';
document.getElementById('changeChatNameButton').style.display = 'none';
chatNameInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
const newName = chatNameInput.value.trim();
if (newName) {
socket.emit('change chat name', newName);
chatNameInput.style.display = 'none';
document.getElementById('chatName').style.display = 'block';
document.getElementById('changeChatNameButton').style.display = 'block';
}
}
});
});
document.getElementById('sendButton').addEventListener('click', () => {
sendMessage();
});
document.getElementById('messageInput').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendMessage();
}
});
document.querySelector('.emoji-button').addEventListener('click', () => {
const emojiPicker = document.getElementById('emojiPicker');
emojiPicker.style.display = emojiPicker.style.display === 'none' ? 'flex' : 'none';
});
document.querySelector('.upload-button').addEventListener('click', () => {
document.getElementById('fileInput').click();
});
document.getElementById('fileInput').addEventListener('change', () => {
const file = document.getElementById('fileInput').files[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
const fileType = file.type.split('/')[0];
if (fileType === 'image') {
socket.emit('image message', e.target.result);
} else if (fileType === 'audio') {
socket.emit('audio message', e.target.result);
} else if (fileType === 'video') {
socket.emit('video message', e.target.result);
}
};
reader.readAsDataURL(file);
}
});
function sendMessage() {
const messageInput = document.getElementById('messageInput');
if (messageInput.value.trim()) {
const formattedMessage = messageInput.value.replace(/:emoji(\d+):/g, (match, p1) => {
return `<img src="emoji/${p1}.png" alt="emoji${p1}" class="emoji">`;
});
socket.emit('chat message', formattedMessage);
messageInput.value = '';
}
}
function appendSystemMessage(msg) {
const item = document.createElement('div');
item.classList.add('system-message');
item.innerText = msg;
document.getElementById('messages').appendChild(item);
document.getElementById('messages').scrollTop = document.getElementById('messages').scrollHeight;
}
function appendMessage(user, msg) {
const item = document.createElement('div');
item.classList.add('message');
if (user.nickname === currentUser) {
item.classList.add('self');
}
item.innerHTML = `
<img src="${user.avatar}" alt="${user.nickname}" class="avatar" οndblclick="openAvatarModal('${user.nickname}')">
<div class="message-bubble">
<span class="username ${user.isOwner ? 'owner' : ''}">${user.nickname}${user.isOwner ? ' (Owner)' : ''}</span>
<div class="message-content">
<div class="message-text">${msg}</div>
</div>
</div>
`;
document.getElementById('messages').appendChild(item);
document.getElementById('messages').scrollTop = document.getElementById('messages').scrollHeight;
}
function appendImageMessage(user, msg) {
const item = document.createElement('div');
item.classList.add('message');
if (user.nickname === currentUser) {
item.classList.add('self');
}
item.innerHTML = `
<img src="${user.avatar}" alt="${user.nickname}" class="avatar" οndblclick="openAvatarModal('${user.nickname}')">
<div class="message-bubble">
<span class="username ${user.isOwner ? 'owner' : ''}">${user.nickname}${user.isOwner ? ' (Owner)' : ''}</span>
<div class="message-content">
<img src="${msg}" alt="Uploaded Image" class="uploaded-image">
</div>
</div>
`;
document.getElementById('messages').appendChild(item);
document.getElementById('messages').scrollTop = document.getElementById('messages').scrollHeight;
}
function appendAudioMessage(user, msg) {
const item = document.createElement('div');
item.classList.add('message');
if (user.nickname === currentUser) {
item.classList.add('self');
}
item.innerHTML = `
<img src="${user.avatar}" alt="${user.nickname}" class="avatar" οndblclick="openAvatarModal('${user.nickname}')">
<div class="message-bubble">
<span class="username ${user.isOwner ? 'owner' : ''}">${user.nickname}${user.isOwner ? ' (Owner)' : ''}</span>
<div class="message-content">
<audio controls>
<source src="${msg}" type="audio/mpeg">
</audio>
</div>
</div>
`;
document.getElementById('messages').appendChild(item);
document.getElementById('messages').scrollTop = document.getElementById('messages').scrollHeight;
}
function appendVideoMessage(user, msg) {
const item = document.createElement('div');
item.classList.add('message');
if (user.nickname === currentUser) {
item.classList.add('self');
}
item.innerHTML = `
<img src="${user.avatar}" alt="${user.nickname}" class="avatar" οndblclick="openAvatarModal('${user.nickname}')">
<div class="message-bubble">
<span class="username ${user.isOwner ? 'owner' : ''}">${user.nickname}${user.isOwner ? ' (Owner)' : ''}</span>
<div class="message-content">
<video controls class="uploaded-video">
<source src="${msg}" type="video/mp4">
</video>
</div>
</div>
`;
document.getElementById('messages').appendChild(item);
document.getElementById('messages').scrollTop = document.getElementById('messages').scrollHeight;
}
function openAvatarModal(nickname) {
if (nickname === currentUser) {
const modal = document.getElementById('avatarModal');
modal.style.display = 'block';
const closeBtn = document.querySelector('.modal .close');
closeBtn.onclick = () => {
modal.style.display = 'none';
};
window.onclick = (event) => {
if (event.target === modal) {
modal.style.display = 'none';
}
};
document.querySelectorAll('.avatar-option').forEach((avatar) => {
avatar.onclick = () => {
socket.emit('change avatar', avatar.src);
modal.style.display = 'none';
};
});
}
}
function updateAvatar(user) {
document.querySelectorAll('.avatar').forEach((avatar) => {
if (avatar.alt === user.nickname) {
avatar.src = user.avatar;
}
});
}
function updateOwner(user) {
document.querySelectorAll('.username').forEach((username) => {
if (username.textContent.includes(user.nickname)) {
username.classList.add('owner');
}
});
}
6. 创建样式文件
在 public
目录下创建一个 styles.css
文件:
/* styles.css */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f0f0f0;
}
#nickname-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
flex-direction: column;
}
.chat-container {
width: 100%;
max-width: 600px;
margin: 50px auto;
background-color: #ffffff;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
display: flex;
flex-direction: column;
justify-content: space-between;
height: 80vh;
position: relative;
}
.chat-header {
background-color: #eeeeee;
padding: 10px;
text-align: center;
font-size: 16px;
font-weight: bold;
border-bottom: 1px solid #ccc;
}
.chat-messages {
padding: 10px;
overflow-y: auto;
flex-grow: 1;
}
.message {
display: flex;
align-items: flex-start;
margin-bottom: 20px;
position: relative;
}
.message.self {
flex-direction: row-reverse;
}
.avatar {
width: 40px;
height: 40px;
border-radius: 50%;
margin: 0 10px;
}
.message-bubble {
display: flex;
flex-direction: column;
align-items: flex-start;
}
.message.self .message-bubble {
align-items: flex-end;
}
.message-content {
background-color: #2f4f4f;
padding: 10px 20px;
border-radius: 15px;
position: relative;
max-width: 60%;
font-size: 14px;
display: flex;
align-items: center;
margin-top: 5px;
}
.message.self .message-content {
background-color: #b0c4de;
}
.username {
font-size: 12px;
color: #888;
margin-bottom: 5px;
}
.username.owner {
color: gold;
font-weight: bold;
}
.message-content::before {
content: "";
position: absolute;
top: 15px;
left: -10px;
width: 0;
height: 0;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
border-right: 10px solid #2f4f4f;
}
.message.self .message-content::before {
left: auto;
right: -10px;
border-right: none;
border-left: 10px solid #b0c4de;
}
.message-text {
color: #ffffff;
}
.message.self .message-text {
color: #000000;
}
.system-message {
text-align: center;
color: #888;
font-size: 14px;
margin: 10px 0;
}
.chat-input-container {
display: flex;
padding: 10px;
border-top: 1px solid #ccc;
}
.chat-input {
flex-grow: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 8px;
font-size: 14px;
margin-right: 10px;
}
.send-button {
padding: 10px 20px;
border: none;
background-color: #007bff;
color: #fff;
border-radius: 8px;
cursor: pointer;
}
.send-button:hover {
background-color: #0056b3;
}
.emoji-button, .upload-button {
padding: 10px;
border: none;
background: none;
cursor: pointer;
font-size: 18px;
margin-right: 10px;
}
.emoji-picker {
position: absolute;
bottom: 60px;
left: 10px;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 8px;
padding: 10px;
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.emoji {
width: 30px;
height: 30px;
cursor: pointer;
}
.uploaded-image, .uploaded-video {
max-width: 100%;
border-radius: 8px;
}
/* Modal styles */
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 5% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
max-width: 600px;
border-radius: 8px;
text-align: center;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
.avatars {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 10px;
margin-top: 20px;
max-height: 300px;
overflow-y: auto;
}
.avatar-option {
width: 60px;
height: 60px;
border-radius: 50%;
cursor: pointer;
border: 2px solid transparent;
}
.avatar-option:hover {
border: 2px solid #007bff;
}
.username.owner {
color: gold;
font-weight: bold;
}
7. 创建表情循环emoji.js
// public/emoji.js
function loadEmojis() {
const emojiPicker = document.getElementById('emojiPicker');
for (let i = 1; i <= 12; i++) {
const emoji = document.createElement('img');
emoji.src = `emoji/${i}.png`;
emoji.alt = `emoji${i}`;
emoji.className = 'emoji';
emoji.addEventListener('click', () => {
const messageInput = document.getElementById('messageInput');
messageInput.value += `:${emoji.alt}:`;
emojiPicker.style.display = 'none';
});
emojiPicker.appendChild(emoji);
}
}
启动服务器
确保您的项目目录结构如下所示:
chat-app/
├── node_modules/
├── public/
│ ├── avatar/
│ │ ├── 10001.png
│ │ ├── 10002.png
│ │ ├── 10003.png
│ │ ├── ...
│ │ └── 10025.png
│ ├── emoji/
│ │ ├── 1.png
│ │ ├── 2.png
│ │ ├── 3.png
│ │ ├── ...
│ │ └── 12.png
│ ├── index.html
│ ├── script.js
│ ├── emoji.js
│ ├── styles.css
├── package.json
└── server.js
然后,在项目根目录下启动服务器:
node server.js
访问 http://localhost:3000
,现在您应该能够使用Node.js和Socket.IO创建的网页聊天室,并支持发送文本、表情、图片、音频和视频消息。