1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
| const express = require('express') const { createServer } = require('http') const { Server } = require('socket.io') const mongoose = require('mongoose') const redis = require('redis') const jwt = require('jsonwebtoken') const cors = require('cors')
const app = express() const httpServer = createServer(app) const io = new Server(httpServer, { cors: { origin: 'http://localhost:5173', methods: ['GET', 'POST'] } })
app.use(cors()) app.use(express.json())
const redisClient = redis.createClient()
mongoose.connect('mongodb://localhost:27017/chatapp')
const User = mongoose.model('User', new mongoose.Schema({ username: String, email: String, password: String, avatar: String, status: { type: String, default: 'offline' }, lastSeen: Date }))
const Message = mongoose.model('Message', new mongoose.Schema({ content: String, type: { type: String, default: 'text' }, sender: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, recipient: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, roomId: String, read: { type: Boolean, default: false }, timestamp: { type: Date, default: Date.now } }))
io.use(async (socket, next) => { try { const token = socket.handshake.auth.token const decoded = jwt.verify(token, process.env.JWT_SECRET) socket.userId = decoded.userId next() } catch (error) { next(new Error('Authentication error')) } })
io.on('connection', async (socket) => { const userId = socket.userId console.log(`用户 ${userId} 已连接`) await User.findByIdAndUpdate(userId, { status: 'online' }) await redisClient.set(`user:${userId}`, socket.id) io.emit('user-online', userId) socket.on('join-room', async (roomId) => { socket.join(roomId) console.log(`用户 ${userId} 加入房间 ${roomId}`) }) socket.on('leave-room', (roomId) => { socket.leave(roomId) }) socket.on('send-message', async (data) => { const message = new Message({ content: data.content, type: data.type || 'text', sender: userId, roomId: data.roomId }) await message.save() const populatedMessage = await Message.findById(message._id) .populate('sender', 'username avatar') io.to(data.roomId).emit('message', populatedMessage) }) socket.on('send-private-message', async (data) => { const message = new Message({ content: data.content, type: data.type || 'text', sender: userId, recipient: data.recipient }) await message.save() const populatedMessage = await Message.findById(message._id) .populate('sender', 'username avatar') const recipientSocketId = await redisClient.get(`user:${data.recipient}`) if (recipientSocketId) { io.to(recipientSocketId).emit('private-message', populatedMessage) } socket.emit('private-message', populatedMessage) }) socket.on('typing', (roomId) => { socket.to(roomId).emit('typing', { userId, roomId }) }) socket.on('mark-read', async (messageId) => { await Message.findByIdAndUpdate(messageId, { read: true }) }) socket.on('disconnect', async () => { console.log(`用户 ${userId} 已断开连接`) await User.findByIdAndUpdate(userId, { status: 'offline', lastSeen: new Date() }) await redisClient.del(`user:${userId}`) io.emit('user-offline', userId) }) })
app.get('/api/messages/:roomId', async (req, res) => { try { const messages = await Message.find({ roomId: req.params.roomId }) .populate('sender', 'username avatar') .sort({ timestamp: -1 }) .limit(50) res.json(messages) } catch (error) { res.status(500).json({ error: error.message }) } })
app.get('/api/users', async (req, res) => { try { const users = await User.find({}, 'username avatar status lastSeen') res.json(users) } catch (error) { res.status(500).json({ error: error.message }) } })
const PORT = process.env.PORT || 3000 httpServer.listen(PORT, () => { console.log(`服务器运行在端口 ${PORT}`) })
|