ajax聊天室创建群聊,js+node.js+socket.io实现聊天功能(私聊,创建群聊)
时间: 2023-06-17 19:04:34 浏览: 196
Node.js websocket使用socket.io库实现实时聊天室
首先,要使用Node.js和Socket.io搭建一个基本的聊天室,可以参考以下步骤:
1. 安装Node.js和npm
2. 创建一个新的Node.js项目并在项目文件夹里打开命令行
3. 在命令行中输入以下命令来安装Socket.io:
```
npm install socket.io
```
4. 创建一个新的文件夹用于存放服务器端代码,我们称之为“server”
5. 在“server”文件夹中创建一个新的JavaScript文件,例如“server.js”
6. 在“server.js”中添加以下代码:
```
const io = require('socket.io')();
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
io.listen(3000);
```
7. 在命令行中进入“server”文件夹并运行“server.js”文件:
```
node server.js
```
8. 创建一个新的文件夹用于存放客户端代码,我们称之为“client”
9. 在“client”文件夹中创建一个新的HTML文件,例如“index.html”
10. 在“index.html”中添加以下代码:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Socket.io Chat Room</title>
</head>
<body>
<h1>Socket.io Chat Room</h1>
<div id="messages"></div>
<form id="message-form">
<input type="text" id="input-message" placeholder="Type your message here...">
<button type="submit">Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-3.0.1.min.js"></script>
<script src="client.js"></script>
</body>
</html>
```
11. 在“client”文件夹中创建一个新的JavaScript文件,例如“client.js”
12. 在“client.js”中添加以下代码:
```
const socket = io('http://localhost:3000');
const messageForm = document.getElementById('message-form');
const inputMessage = document.getElementById('input-message');
const messages = document.getElementById('messages');
messageForm.addEventListener('submit', (event) => {
event.preventDefault();
const message = inputMessage.value;
if (message) {
socket.emit('chat message', message);
inputMessage.value = '';
}
});
socket.on('chat message', (message) => {
const li = document.createElement('li');
li.textContent = message;
messages.appendChild(li);
});
```
13. 在命令行中进入“client”文件夹并运行以下命令:
```
npm install express
```
14. 在“client”文件夹中创建一个新的JavaScript文件,例如“server.js”
15. 在“server.js”中添加以下代码:
```
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(8080, () => {
console.log('Server running on http://localhost:8080');
});
```
16. 在命令行中进入“client”文件夹并运行以下命令:
```
node server.js
```
现在你就可以在浏览器中打开“http://localhost:8080”并开始聊天了。
要实现私聊和创建群聊的功能,你需要在服务器端和客户端中添加一些额外的代码。
对于私聊功能,你可以创建一个“私聊房间”,只有被邀请的用户才能加入该房间,并在该房间中进行私人对话。以下是一些可能有用的代码:
1. 服务器端:
```
const users = {};
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('login', (username) => {
users[username] = socket.id;
console.log(`${username} logged in`);
});
socket.on('invite', (username) => {
const roomId = `${socket.id}:${users[username]}`;
socket.join(roomId);
io.to(users[username]).emit('invited', roomId);
});
socket.on('chat message', (data) => {
const { message, roomId } = data;
io.to(roomId).emit('chat message', message);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
```
2. 客户端:
```
const socket = io('http://localhost:3000');
const username = prompt('What is your name?');
socket.emit('login', username);
let roomId = null;
const inviteForm = document.getElementById('invite-form');
const inviteInput = document.getElementById('invite-input');
inviteForm.addEventListener('submit', (event) => {
event.preventDefault();
const username = inviteInput.value;
if (username) {
socket.emit('invite', username);
inviteInput.value = '';
}
});
socket.on('invited', (id) => {
roomId = id;
messages.innerHTML = '';
messageForm.style.display = 'block';
});
messageForm.addEventListener('submit', (event) => {
event.preventDefault();
const message = inputMessage.value;
if (message) {
socket.emit('chat message', { message, roomId });
inputMessage.value = '';
}
});
socket.on('chat message', (message) => {
const li = document.createElement('li');
li.textContent = message;
messages.appendChild(li);
});
```
对于创建群聊功能,你可以创建一个“群聊房间”,所有用户都可以加入该房间,并在该房间中进行群聊。以下是一些可能有用的代码:
1. 服务器端:
```
const rooms = {};
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('create room', () => {
const roomId = socket.id;
socket.join(roomId);
rooms[roomId] = { name: `Room ${Object.keys(rooms).length + 1}` };
io.to(roomId).emit('room created', roomId);
console.log(`Room ${roomId} created`);
});
socket.on('join room', (roomId) => {
socket.join(roomId);
io.to(roomId).emit('user joined', { username: 'anonymous', message: 'joined the chat' });
console.log(`User ${socket.id} joined room ${roomId}`);
});
socket.on('chat message', (data) => {
const { message, roomId } = data;
io.to(roomId).emit('chat message', message);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
```
2. 客户端:
```
const socket = io('http://localhost:3000');
const createRoomButton = document.getElementById('create-room-button');
const joinRoomForm = document.getElementById('join-room-form');
const joinRoomInput = document.getElementById('join-room-input');
createRoomButton.addEventListener('click', () => {
socket.emit('create room');
});
joinRoomForm.addEventListener('submit', (event) => {
event.preventDefault();
const roomId = joinRoomInput.value;
if (roomId) {
socket.emit('join room', roomId);
joinRoomInput.value = '';
messages.innerHTML = '';
messageForm.style.display = 'block';
}
});
socket.on('room created', (roomId) => {
const option = document.createElement('option');
option.value = roomId;
option.textContent = `Room ${Object.keys(rooms).length}`;
selectRoom.appendChild(option);
});
socket.on('user joined', (data) => {
const { username, message } = data;
const li = document.createElement('li');
li.textContent = `${username} ${message}`;
messages.appendChild(li);
});
socket.on('chat message', (message) => {
const li = document.createElement('li');
li.textContent = message;
messages.appendChild(li);
});
```
以上代码只是一个简单的示例,你可以根据自己的需求进行更改和扩展。
阅读全文