forked from cainiaopppppppp/MeshKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsignaling-server.js
More file actions
500 lines (419 loc) · 12.7 KB
/
signaling-server.js
File metadata and controls
500 lines (419 loc) · 12.7 KB
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
// signaling-server.js - 修复版
const WebSocket = require('ws');
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 8000;
// MIME类型映射
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon'
};
// 创建 HTTP 服务器
const server = http.createServer((req, res) => {
console.log('请求:', req.url);
// 根路径返回 index.html
if (req.url === '/') {
req.url = '/index.html';
}
// 处理静态文件
const filePath = path.join(__dirname, req.url);
const extname = path.extname(filePath).toLowerCase();
const contentType = mimeTypes[extname] || 'application/octet-stream';
// 检查文件是否存在
fs.access(filePath, fs.constants.F_OK, (err) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
res.end('404 Not Found');
return;
}
// 读取并返回文件
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
res.end('500 Internal Server Error');
return;
}
res.writeHead(200, { 'Content-Type': contentType + '; charset=utf-8' });
res.end(data);
});
});
});
// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ server });
// 存储所有连接的设备
const devices = new Map();
// 存储所有房间
const rooms = new Map();
wss.on('connection', (ws, req) => {
const clientIp = req.socket.remoteAddress;
console.log('✅ 新设备连接:', clientIp);
let deviceId = null;
ws.on('message', (message) => {
try {
const data = JSON.parse(message);
switch (data.type) {
case 'register':
deviceId = data.deviceId;
devices.set(deviceId, {
id: deviceId,
name: data.deviceName,
ws: ws,
timestamp: Date.now()
});
console.log(`📱 设备注册: ${data.deviceName} (${deviceId})`);
// 广播设备列表
broadcastDeviceList();
break;
case 'offer':
case 'answer':
case 'ice-candidate':
// 转发信令消息
const targetDevice = devices.get(data.target);
if (targetDevice && targetDevice.ws.readyState === WebSocket.OPEN) {
targetDevice.ws.send(JSON.stringify({
type: data.type,
from: deviceId,
data: data.data
}));
}
break;
case 'heartbeat':
// 心跳
if (deviceId && devices.has(deviceId)) {
devices.get(deviceId).timestamp = Date.now();
}
break;
case 'create-room':
handleCreateRoom(data, ws);
break;
case 'join-room':
handleJoinRoom(data, ws);
break;
case 'leave-room':
handleLeaveRoom(data);
break;
case 'start-broadcast':
handleStartBroadcast(data);
break;
case 'update-room-files':
handleUpdateRoomFiles(data);
break;
case 'request-file':
handleRequestFile(data);
break;
}
} catch (error) {
console.error('❌ 消息处理错误:', error);
}
});
ws.on('close', () => {
if (deviceId) {
console.log(`👋 设备断开: ${deviceId}`);
devices.delete(deviceId);
broadcastDeviceList();
}
});
ws.on('error', (error) => {
console.error('❌ WebSocket 错误:', error);
});
});
// 广播设备列表
function broadcastDeviceList() {
const deviceList = Array.from(devices.values()).map(device => ({
id: device.id,
name: device.name,
timestamp: device.timestamp
}));
const message = JSON.stringify({
type: 'device-list',
devices: deviceList
});
console.log(`📡 广播设备列表 (共 ${deviceList.length} 个设备)`);
devices.forEach(device => {
if (device.ws.readyState === WebSocket.OPEN) {
device.ws.send(message);
}
});
}
// 生成6位房间号
function generateRoomId() {
let roomId;
do {
roomId = Math.floor(100000 + Math.random() * 900000).toString();
} while (rooms.has(roomId));
return roomId;
}
// 向房间内所有成员广播消息
function broadcastToRoom(room, message, excludeDeviceId = null) {
// 🔒 确保不泄露密码
if (message.room && message.room.password) {
message = {
...message,
room: {
...message.room,
hasPassword: true
}
};
delete message.room.password;
}
room.members.forEach(member => {
if (member.deviceId !== excludeDeviceId) {
const device = devices.get(member.deviceId);
if (device && device.ws.readyState === WebSocket.OPEN) {
device.ws.send(JSON.stringify(message));
}
}
});
}
// 处理创建房间
function handleCreateRoom(data, ws) {
const { deviceId, deviceName, data: roomData } = data;
const { fileInfo, fileList, isMultiFile, password } = roomData;
const roomId = generateRoomId();
const room = {
id: roomId,
name: `Room ${roomId}`,
hostId: deviceId,
members: [{
deviceId,
deviceName,
role: 'host',
status: 'waiting',
joinedAt: Date.now()
}],
createdAt: Date.now(),
fileInfo,
fileList: isMultiFile ? fileList : undefined,
isMultiFile: isMultiFile || false,
status: 'waiting',
password: password || null // 存储密码(如果有)
};
rooms.set(roomId, room);
console.log(`🏠 房间创建成功: ${roomId} by ${deviceName}${password ? ' 🔒 (有密码保护)' : ''}`);
// 发送房间创建成功消息(不包含密码)
const roomInfo = { ...room };
delete roomInfo.password; // 不发送密码给客户端
roomInfo.hasPassword = !!password; // 但告知是否有密码
ws.send(JSON.stringify({
type: 'room-update',
room: roomInfo
}));
}
// 处理加入房间
function handleJoinRoom(data, ws) {
const { deviceId, deviceName, roomId, password } = data;
console.log(`[DEBUG] 加入房间请求 - 房间: ${roomId}, 用户: ${deviceName}, 提供的密码: ${password === undefined ? 'undefined' : password === null ? 'null' : `"${password}"`}`);
const room = rooms.get(roomId);
if (!room) {
ws.send(JSON.stringify({
type: 'room-error',
error: '房间不存在'
}));
return;
}
console.log(`[DEBUG] 房间密码状态 - 房间密码: ${room.password === undefined ? 'undefined' : room.password === null ? 'null' : `"${room.password}"`}`);
// 🔒 严格验证密码(如果房间有密码保护)
if (room.password !== null && room.password !== undefined && room.password !== '') {
console.log(`[DEBUG] 房间需要密码验证`);
// 必须提供密码
if (password === undefined || password === null) {
console.log(`❌ ${deviceName} 未提供密码,无法加入房间: ${roomId}`);
ws.send(JSON.stringify({
type: 'room-error',
error: '此房间需要密码'
}));
return;
}
// 密码不能为空
if (typeof password !== 'string' || password.trim() === '') {
console.log(`❌ ${deviceName} 密码为空,无法加入房间: ${roomId}`);
ws.send(JSON.stringify({
type: 'room-error',
error: '密码不能为空'
}));
return;
}
// 密码必须匹配
if (password !== room.password) {
console.log(`❌ ${deviceName} 密码错误,无法加入房间: ${roomId} (提供: "${password}", 正确: "${room.password}")`);
ws.send(JSON.stringify({
type: 'room-error',
error: '密码错误'
}));
return;
}
console.log(`✅ ${deviceName} 密码验证成功`);
} else {
console.log(`[DEBUG] 房间无密码保护,直接允许加入`);
}
// 检查是否已经在房间中
const existingMember = room.members.find(m => m.deviceId === deviceId);
if (existingMember) {
// 已在房间中,直接返回房间信息(不包含密码)
const roomInfo = { ...room };
delete roomInfo.password;
roomInfo.hasPassword = !!room.password;
ws.send(JSON.stringify({
type: 'room-update',
room: roomInfo
}));
return;
}
// 添加新成员
room.members.push({
deviceId,
deviceName,
role: 'member',
status: 'waiting',
joinedAt: Date.now()
});
console.log(`👤 ${deviceName} 加入房间: ${roomId}${room.password ? ' (密码验证通过)' : ''}`);
// 移除密码字段,只广播必要信息
const roomInfo = { ...room };
delete roomInfo.password;
roomInfo.hasPassword = !!room.password;
// 向所有成员广播房间更新(包括新加入的成员)
broadcastToRoom(room, {
type: 'room-update',
room: roomInfo
});
// 向新成员发送房间信息
ws.send(JSON.stringify({
type: 'room-update',
room: roomInfo
}));
}
// 处理离开房间
function handleLeaveRoom(data) {
const { deviceId, roomId } = data;
const room = rooms.get(roomId);
if (!room) return;
// 移除成员
room.members = room.members.filter(m => m.deviceId !== deviceId);
console.log(`👋 设备离开房间: ${deviceId} from ${roomId}`);
// 如果房主离开或房间为空,删除房间
if (deviceId === room.hostId || room.members.length === 0) {
console.log(`🗑️ 删除房间: ${roomId}`);
rooms.delete(roomId);
// 通知所有成员房间已关闭
broadcastToRoom(room, {
type: 'room-error',
error: '房间已关闭'
});
} else {
// 通知其他成员
broadcastToRoom(room, {
type: 'room-update',
room
});
}
}
// 处理开始广播
function handleStartBroadcast(data) {
const { roomId } = data;
const room = rooms.get(roomId);
if (!room) return;
room.status = 'transferring';
console.log(`📡 开始广播: ${roomId}`);
// 通知所有成员开始传输
broadcastToRoom(room, {
type: 'room-update',
room
});
}
// 处理更新房间文件列表(添加/删除文件)
function handleUpdateRoomFiles(data) {
const { roomId, fileList } = data;
const room = rooms.get(roomId);
if (!room) return;
room.fileList = fileList;
room.isMultiFile = fileList && fileList.length > 1;
console.log(`📝 更新房间文件列表: ${roomId}, ${fileList.length} 个文件`);
// 通知所有成员文件列表已更新
broadcastToRoom(room, {
type: 'room-update',
room
});
}
// 处理文件下载请求(接收方请求特定文件)
function handleRequestFile(data) {
const { roomId, deviceId, fileIndex } = data;
const room = rooms.get(roomId);
if (!room) return;
console.log(`📥 文件下载请求: Room ${roomId}, File ${fileIndex} by ${deviceId}`);
// 转发请求给房主
const host = devices.get(room.hostId);
if (host && host.ws.readyState === WebSocket.OPEN) {
host.ws.send(JSON.stringify({
type: 'file-request',
from: deviceId,
fileIndex
}));
}
}
// 定期清理离线设备
setInterval(() => {
const now = Date.now();
let cleaned = false;
devices.forEach((device, id) => {
if (now - device.timestamp > 15000) { // 15秒超时
console.log(`🧹 清理离线设备: ${id}`);
devices.delete(id);
cleaned = true;
}
});
if (cleaned) {
broadcastDeviceList();
}
}, 5000);
// 获取本机IP地址
function getLocalIP() {
const os = require('os');
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
// 跳过内部和非IPv4地址
if (iface.family === 'IPv4' && !iface.internal) {
return iface.address;
}
}
}
return '127.0.0.1';
}
server.listen(PORT, '0.0.0.0', () => {
const localIP = getLocalIP();
console.log('');
console.log('=================================');
console.log('🚀 局域网传输服务器已启动!');
console.log('=================================');
console.log('');
console.log('📱 在电脑和手机上访问:');
console.log('');
console.log(` http://${localIP}:${PORT}`);
console.log('');
console.log(' 或者');
console.log('');
console.log(` http://localhost:${PORT}`);
console.log('');
console.log('=================================');
console.log('');
console.log('💡 提示:');
console.log(' - 模块化架构,易于扩展');
console.log(' - 电脑和手机需要在同一WiFi');
console.log(' - 按 Ctrl+C 停止服务器');
console.log('');
console.log('📂 支持的文件:');
console.log(' - HTML, JS, CSS (模块化)');
console.log(' - 静态资源 (图片等)');
console.log('');
console.log('📊 服务器日志:');
console.log('');
});