const express = require('express'); const http = require('http'); const WebSocket = require('ws'); const multer = require('multer'); const path = require('path'); const fs = require('fs'); if (!fs.existsSync(path.join(__dirname, 'public', 'uploads'))) { fs.mkdirSync(path.join(__dirname, 'public', 'uploads')); } const app = express(); const server = http.createServer(app); const wss = new WebSocket.Server({ server }); // 设置文件上传存储路径和文件名 const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'public/uploads/'); }, filename: function (req, file, cb) { cb(null, file.originalname); } }); const upload = multer({ storage: storage }); // 静态文件服务 app.use(express.static(path.join(__dirname, 'public'))); // 处理文件上传 app.post('/upload', upload.single('file'), (req, res) => { const fileUrl = `http://localhost:3000/uploads/${req.file.filename}`; wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify({ type: 'file', url: fileUrl })); } }); res.send('File uploaded successfully!'); }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { const result = JSON.stringify({ type: 'message', msg: message.toString() }); client.send(result); } }); }); ws.on('close', function close() { console.log('Client disconnected'); }); }); server.listen(3000, () => { console.log('Server started on http://localhost:3000'); });