帮我从0-1利用express=mysql+ws搭建一个可能和不同的客户端单聊群聊的实时通讯
时间: 2024-04-22 16:27:40 浏览: 138
即时通讯,单聊,和群聊,maven 工程,直接部署
好的,我会给您提供一份简单的代码示例,演示如何使用Express、MySQL和WebSocket搭建一个实时通讯应用程序,包括单聊和群聊。请注意,以下代码示例仅供参考,您需要根据您的具体需求进行修改和调整。
首先,我们需要安装必要的模块。在命令行中运行以下命令:
```
npm install express mysql ws
```
接下来,我们需要创建一个MySQL数据库和表来存储用户信息和聊天记录。以下是一个简单的SQL脚本,可以创建一个名为“chat”的数据库和两个表“users”和“messages”:
```sql
CREATE DATABASE chat;
USE chat;
CREATE TABLE users (
id INT(11) NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE messages (
id INT(11) NOT NULL AUTO_INCREMENT,
sender VARCHAR(50) NOT NULL,
receiver VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
```
接下来,我们需要创建一个Express应用程序,并在端口3000上启动它:
```javascript
const express = require('express');
const mysql = require('mysql');
const WebSocket = require('ws');
const app = express();
const server = app.listen(3000, () => {
console.log('Server started on port 3000');
});
const wss = new WebSocket.Server({ server });
// MySQL连接配置
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'chat'
});
// 连接MySQL数据库
db.connect((err) => {
if (err) {
throw err;
}
console.log('MySQL connected');
});
// 处理WebSocket连接
wss.on('connection', (ws) => {
console.log('Client connected');
// 处理收到的消息
ws.on('message', (message) => {
console.log(`Received message => ${message}`);
// 解析消息
const data = JSON.parse(message);
// 处理不同类型的消息
switch (data.type) {
case 'login':
handleLogin(ws, data.username, data.password);
break;
case 'register':
handleRegister(ws, data.username, data.password);
break;
case 'chat':
handleChat(ws, data.sender, data.receiver, data.content);
break;
case 'groupchat':
handleGroupChat(ws, data.sender, data.content);
break;
default:
break;
}
});
// 处理WebSocket关闭
ws.on('close', () => {
console.log('Client disconnected');
});
// 处理WebSocket错误
ws.on('error', (err) => {
console.error(`WebSocket error: ${err}`);
});
});
// 处理用户登录
function handleLogin(ws, username, password) {
const sql = `SELECT * FROM users WHERE username='${username}' AND password='${password}'`;
db.query(sql, (err, results) => {
if (err) {
console.error(`MySQL error: ${err}`);
return;
}
if (results.length === 0) {
ws.send(JSON.stringify({ type: 'login', success: false }));
} else {
ws.send(JSON.stringify({ type: 'login', success: true }));
}
});
}
// 处理用户注册
function handleRegister(ws, username, password) {
const sql = `INSERT INTO users (username, password) VALUES ('${username}', '${password}')`;
db.query(sql, (err, result) => {
if (err) {
console.error(`MySQL error: ${err}`);
ws.send(JSON.stringify({ type: 'register', success: false }));
} else {
ws.send(JSON.stringify({ type: 'register', success: true }));
}
});
}
// 处理单聊消息
function handleChat(ws, sender, receiver, content) {
const sql = `INSERT INTO messages (sender, receiver, content) VALUES ('${sender}', '${receiver}', '${content}')`;
db.query(sql, (err, result) => {
if (err) {
console.error(`MySQL error: ${err}`);
return;
}
// 查找接收者的WebSocket连接
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
const user = JSON.parse(client.user);
if (user.username === receiver) {
// 给接收者发送消息
client.send(JSON.stringify({ type: 'chat', sender, content }));
}
}
});
});
}
// 处理群聊消息
function handleGroupChat(ws, sender, content) {
const sql = `INSERT INTO messages (sender, receiver, content) VALUES ('${sender}', 'all', '${content}')`;
db.query(sql, (err, result) => {
if (err) {
console.error(`MySQL error: ${err}`);
return;
}
// 给所有客户端发送消息
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type: 'groupchat', sender, content }));
}
});
});
}
```
在上面的代码中,我们首先创建了一个MySQL连接,并在WebSocket连接中处理收到的消息。根据不同的消息类型,我们调用不同的处理函数来处理消息。在处理函数中,我们查询数据库、插入记录或者发送消息给客户端。
现在,我们需要编写前端代码来连接到WebSocket服务器并发送和接收消息。以下是一个简单的HTML页面,可以让用户输入用户名和密码来登录或注册:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Chat</title>
</head>
<body>
<h1>Chat</h1>
<form>
<label>Username:</label>
<input type="text" id="username" required>
<br>
<label>Password:</label>
<input type="password" id="password" required>
<br>
<button type="submit" id="login">Login</button>
<button type="submit" id="register">Register</button>
</form>
<hr>
<h2>Chat Room</h2>
<div id="chat"></div>
<form>
<label>Receiver:</label>
<input type="text" id="receiver" required>
<br>
<label>Message:</label>
<input type="text" id="message" required>
<br>
<button type="submit" id="send">Send</button>
</form>
<hr>
<h2>Group Chat Room</h2>
<div id="groupchat"></div>
<form>
<label>Message:</label>
<input type="text" id="groupmessage" required>
<br>
<button type="submit" id="groupsend">Send</button>
</form>
<script>
const ws = new WebSocket('ws://localhost:3000');
ws.onopen = () => {
console.log('WebSocket connected');
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
switch (data.type) {
case 'login':
if (data.success) {
console.log('Login succeeded');
} else {
console.log('Login failed');
}
break;
case 'register':
if (data.success) {
console.log('Register succeeded');
} else {
console.log('Register failed');
}
break;
case 'chat':
const chat = document.querySelector('#chat');
const message = document.createElement('p');
message.textContent = `${data.sender}: ${data.content}`;
chat.appendChild(message);
break;
case 'groupchat':
const groupchat = document.querySelector('#groupchat');
const groupmessage = document.createElement('p');
groupmessage.textContent = `${data.sender}: ${data.content}`;
groupchat.appendChild(groupmessage);
break;
default:
break;
}
};
document.querySelector('#login').addEventListener('click', (event) => {
event.preventDefault();
const username = document.querySelector('#username').value;
const password = document.querySelector('#password').value;
const data = { type: 'login', username, password };
ws.send(JSON.stringify(data));
});
document.querySelector('#register').addEventListener('click', (event) => {
event.preventDefault();
const username = document.querySelector('#username').value;
const password = document.querySelector('#password').value;
const data = { type: 'register', username, password };
ws.send(JSON.stringify(data));
});
document.querySelector('#send').addEventListener('click', (event) => {
event.preventDefault();
const sender = document.querySelector('#username').value;
const receiver = document.querySelector('#receiver').value;
const content = document.querySelector('#message').value;
const data = { type: 'chat', sender, receiver, content };
ws.send(JSON.stringify(data));
});
document.querySelector('#groupsend').addEventListener('click', (event) => {
event.preventDefault();
const sender = document.querySelector('#username').value;
const content = document.querySelector('#groupmessage').value;
const data = { type: 'groupchat', sender, content };
ws.send(JSON.stringify(data));
});
</script>
</body>
</html>
```
在上面的代码中,我们创建了一个WebSocket连接,并在收到消息时更新聊天室的消息。我们还在页面上添加了一个表单来让用户输入要发送的消息。注意,我们将用户名和密码存储在输入框中,这不是一个安全的做法,您需要根据您的具体需求进行修改。
现在,您可以运行这个应用程序,并在浏览器中访问它。您可以使用不同的标签页或浏览器窗口来模拟不同的用户,然后在聊天室中发送消息。如果您想要测试群聊功能,可以在“Receiver”输入框中输入“all”。
希望这个示例对您有所帮助!
阅读全文