mirror of
https://github.com/imputnet/cobalt.git
synced 2025-06-28 09:28:29 +00:00
加入日志
This commit is contained in:
parent
1134825d80
commit
733c964eb4
@ -9,29 +9,32 @@ export const setupSignalingServer = (httpServer) => {
|
|||||||
|
|
||||||
const sessions = new Map(); // sessionId -> { creator, joiner, createdAt }
|
const sessions = new Map(); // sessionId -> { creator, joiner, createdAt }
|
||||||
|
|
||||||
console.log(`${Green('[✓]')} WebSocket信令服务器启动成功,监听路径: /ws`);
|
console.log(`${Green('[✓]')} WebSocket signaling server started successfully, listening on path: /ws`);
|
||||||
|
|
||||||
// 清理过期会话
|
// Clean up expired sessions
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
for (const [sessionId, session] of sessions.entries()) {
|
for (const [sessionId, session] of sessions.entries()) {
|
||||||
if (now - session.createdAt > 30 * 60 * 1000) { // 30分钟过期
|
if (now - session.createdAt > 30 * 60 * 1000) { // 30 minutes expiration
|
||||||
sessions.delete(sessionId);
|
sessions.delete(sessionId);
|
||||||
console.log(`清理过期会话: ${sessionId}`);
|
console.log(`Cleaned up expired session: ${sessionId}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, 5 * 60 * 1000); // 每5分钟检查一次
|
}, 5 * 60 * 1000); // Check every 5 minutes
|
||||||
|
|
||||||
wss.on('connection', (ws, req) => {
|
wss.on('connection', (ws, req) => {
|
||||||
const clientIP = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.socket.remoteAddress;
|
const clientIP = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.socket.remoteAddress;
|
||||||
console.log('WebSocket连接建立:', clientIP, 'URL:', req.url);
|
const userAgent = req.headers['user-agent'] || 'Unknown';
|
||||||
|
console.log(`WebSocket connection established: ${clientIP}, URL: ${req.url}, User-Agent: ${userAgent}`);
|
||||||
|
|
||||||
let sessionId = null;
|
let sessionId = null;
|
||||||
let userRole = null; // 'creator' | 'joiner'
|
let userRole = null; // 'creator' | 'joiner'
|
||||||
|
let connectionStartTime = Date.now();
|
||||||
|
|
||||||
ws.on('message', (data) => {
|
ws.on('message', (data) => {
|
||||||
try {
|
try {
|
||||||
const message = JSON.parse(data);
|
const message = JSON.parse(data);
|
||||||
|
console.log(`Received message type: ${message.type} from ${userRole || 'unknown'} in session ${sessionId || 'none'}`);
|
||||||
|
|
||||||
switch (message.type) {
|
switch (message.type) {
|
||||||
case 'create_session':
|
case 'create_session':
|
||||||
@ -49,35 +52,43 @@ export const setupSignalingServer = (httpServer) => {
|
|||||||
handleDisconnect(sessionId, userRole);
|
handleDisconnect(sessionId, userRole);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
|
console.log(`Unknown message type: ${message.type}`);
|
||||||
ws.send(JSON.stringify({
|
ws.send(JSON.stringify({
|
||||||
type: 'error',
|
type: 'error',
|
||||||
message: '未知消息类型'
|
message: 'Unknown message type'
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('WebSocket消息处理错误:', error);
|
console.error(`WebSocket message processing error (sessionId: ${sessionId || 'None'}):`, error);
|
||||||
ws.send(JSON.stringify({
|
ws.send(JSON.stringify({
|
||||||
type: 'error',
|
type: 'error',
|
||||||
message: '消息格式错误'
|
message: 'Message format error'
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
ws.on('close', () => {
|
ws.on('close', (code, reason) => {
|
||||||
console.log('WebSocket连接关闭');
|
const connectionDuration = Date.now() - connectionStartTime;
|
||||||
|
const reasonStr = reason ? reason.toString() : 'No reason provided';
|
||||||
|
console.log(`WebSocket connection closed: code=${code}, reason="${reasonStr}", sessionId=${sessionId || 'None'}, role=${userRole || 'None'}, duration=${connectionDuration}ms`);
|
||||||
|
|
||||||
if (sessionId && userRole) {
|
if (sessionId && userRole) {
|
||||||
handleDisconnect(sessionId, userRole);
|
handleDisconnect(sessionId, userRole);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
ws.on('error', (error) => {
|
ws.on('error', (error) => {
|
||||||
console.error('WebSocket错误:', error);
|
console.error(`WebSocket error (sessionId: ${sessionId || 'None'}, role: ${userRole || 'None'}):`, error.message || error);
|
||||||
}); function handleCreateSession(ws, message) {
|
});
|
||||||
// 检查是否提供了现有会话ID(用于重连)
|
|
||||||
|
function handleCreateSession(ws, message) {
|
||||||
|
console.log(`Handling create session request, existing sessionId: ${message.existingSessionId || 'None'}`);
|
||||||
|
|
||||||
|
// Check if existing session ID is provided (for reconnection)
|
||||||
if (message.existingSessionId) {
|
if (message.existingSessionId) {
|
||||||
const existingSession = sessions.get(message.existingSessionId);
|
const existingSession = sessions.get(message.existingSessionId);
|
||||||
if (existingSession && !existingSession.creator) {
|
if (existingSession && !existingSession.creator) {
|
||||||
// 重连到现有会话
|
// Reconnect to existing session
|
||||||
sessionId = message.existingSessionId;
|
sessionId = message.existingSessionId;
|
||||||
userRole = 'creator';
|
userRole = 'creator';
|
||||||
existingSession.creator = { ws, publicKey: message.publicKey };
|
existingSession.creator = { ws, publicKey: message.publicKey };
|
||||||
@ -87,7 +98,7 @@ export const setupSignalingServer = (httpServer) => {
|
|||||||
sessionId: sessionId
|
sessionId: sessionId
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// 如果有在线的 joiner,通知双方重新建立连接
|
// If there's an online joiner, notify both parties to re-establish connection
|
||||||
if (existingSession.joiner && existingSession.joiner.ws.readyState === ws.OPEN) {
|
if (existingSession.joiner && existingSession.joiner.ws.readyState === ws.OPEN) {
|
||||||
existingSession.joiner.ws.send(JSON.stringify({
|
existingSession.joiner.ws.send(JSON.stringify({
|
||||||
type: 'creator_reconnected',
|
type: 'creator_reconnected',
|
||||||
@ -100,12 +111,12 @@ export const setupSignalingServer = (httpServer) => {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`创建者重连会话: ${sessionId}`);
|
console.log(`Creator reconnected to session: ${sessionId}`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建新会话
|
// Create new session
|
||||||
sessionId = Math.random().toString(36).substring(2, 10);
|
sessionId = Math.random().toString(36).substring(2, 10);
|
||||||
userRole = 'creator';
|
userRole = 'creator';
|
||||||
|
|
||||||
@ -120,23 +131,28 @@ export const setupSignalingServer = (httpServer) => {
|
|||||||
sessionId: sessionId
|
sessionId: sessionId
|
||||||
}));
|
}));
|
||||||
|
|
||||||
console.log(`会话创建: ${sessionId}`);
|
console.log(`Session created: ${sessionId}`);
|
||||||
}function handleJoinSession(ws, message) {
|
}
|
||||||
|
|
||||||
|
function handleJoinSession(ws, message) {
|
||||||
|
console.log(`Handling join session request for sessionId: ${message.sessionId}`);
|
||||||
const session = sessions.get(message.sessionId);
|
const session = sessions.get(message.sessionId);
|
||||||
|
|
||||||
if (!session) {
|
if (!session) {
|
||||||
|
console.log(`Session not found: ${message.sessionId}`);
|
||||||
ws.send(JSON.stringify({
|
ws.send(JSON.stringify({
|
||||||
type: 'error',
|
type: 'error',
|
||||||
message: '会话不存在或已过期'
|
message: 'Session does not exist or has expired'
|
||||||
}));
|
}));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查是否已有活跃的 joiner
|
// Check if there's already an active joiner
|
||||||
if (session.joiner && session.joiner.ws.readyState === ws.OPEN) {
|
if (session.joiner && session.joiner.ws.readyState === ws.OPEN) {
|
||||||
|
console.log(`Session full: ${message.sessionId}`);
|
||||||
ws.send(JSON.stringify({
|
ws.send(JSON.stringify({
|
||||||
type: 'error',
|
type: 'error',
|
||||||
message: '会话已满'
|
message: 'Session is full'
|
||||||
}));
|
}));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -144,63 +160,70 @@ export const setupSignalingServer = (httpServer) => {
|
|||||||
sessionId = message.sessionId;
|
sessionId = message.sessionId;
|
||||||
userRole = 'joiner';
|
userRole = 'joiner';
|
||||||
|
|
||||||
// 设置或重新设置 joiner
|
// Set or reset joiner
|
||||||
session.joiner = { ws, publicKey: message.publicKey };
|
session.joiner = { ws, publicKey: message.publicKey };
|
||||||
|
|
||||||
// 通知创建者有人加入(如果创建者在线)
|
// Notify creator that someone joined (if creator is online)
|
||||||
if (session.creator && session.creator.ws.readyState === ws.OPEN) {
|
if (session.creator && session.creator.ws.readyState === ws.OPEN) {
|
||||||
session.creator.ws.send(JSON.stringify({
|
session.creator.ws.send(JSON.stringify({
|
||||||
type: 'peer_joined',
|
type: 'peer_joined',
|
||||||
publicKey: message.publicKey
|
publicKey: message.publicKey
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// 回复加入者创建者的公钥
|
// Reply to joiner with creator's public key
|
||||||
ws.send(JSON.stringify({
|
ws.send(JSON.stringify({
|
||||||
type: 'session_joined',
|
type: 'session_joined',
|
||||||
publicKey: session.creator.publicKey
|
publicKey: session.creator.publicKey
|
||||||
}));
|
}));
|
||||||
|
|
||||||
console.log(`用户重连到会话: ${sessionId}`);
|
console.log(`User joined session: ${sessionId}`);
|
||||||
} else {
|
} else {
|
||||||
// 创建者不在线,通知加入者等待
|
// Creator is not online, notify joiner to wait
|
||||||
ws.send(JSON.stringify({
|
ws.send(JSON.stringify({
|
||||||
type: 'waiting_for_creator',
|
type: 'waiting_for_creator',
|
||||||
message: '等待创建者重新连接'
|
message: 'Waiting for creator to reconnect'
|
||||||
}));
|
}));
|
||||||
console.log(`加入者在线,等待创建者: ${sessionId}`);
|
console.log(`Joiner online, waiting for creator: ${sessionId}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleSignaling(ws, message, sessionId, userRole) {
|
function handleSignaling(ws, message, sessionId, userRole) {
|
||||||
if (!sessionId || !userRole) {
|
if (!sessionId || !userRole) {
|
||||||
|
console.log(`Signaling error: not joined to session (sessionId: ${sessionId}, role: ${userRole})`);
|
||||||
ws.send(JSON.stringify({
|
ws.send(JSON.stringify({
|
||||||
type: 'error',
|
type: 'error',
|
||||||
message: '未加入会话'
|
message: 'Not joined to any session'
|
||||||
}));
|
}));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const session = sessions.get(sessionId);
|
const session = sessions.get(sessionId);
|
||||||
if (!session) {
|
if (!session) {
|
||||||
|
console.log(`Signaling error: session not found (sessionId: ${sessionId})`);
|
||||||
ws.send(JSON.stringify({
|
ws.send(JSON.stringify({
|
||||||
type: 'error',
|
type: 'error',
|
||||||
message: '会话不存在'
|
message: 'Session does not exist'
|
||||||
}));
|
}));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 转发信令消息给对端
|
// Forward signaling message to peer
|
||||||
const peer = userRole === 'creator' ? session.joiner : session.creator;
|
const peer = userRole === 'creator' ? session.joiner : session.creator;
|
||||||
if (peer && peer.ws.readyState === ws.OPEN) {
|
if (peer && peer.ws.readyState === ws.OPEN) {
|
||||||
peer.ws.send(JSON.stringify(message));
|
peer.ws.send(JSON.stringify(message));
|
||||||
|
console.log(`Signaling message forwarded: ${message.type} from ${userRole} in session ${sessionId}`);
|
||||||
|
} else {
|
||||||
|
console.log(`Signaling failed: peer not available (sessionId: ${sessionId}, userRole: ${userRole})`);
|
||||||
}
|
}
|
||||||
} function handleDisconnect(sessionId, userRole) {
|
}
|
||||||
|
|
||||||
|
function handleDisconnect(sessionId, userRole) {
|
||||||
if (!sessionId) return;
|
if (!sessionId) return;
|
||||||
|
|
||||||
const session = sessions.get(sessionId);
|
const session = sessions.get(sessionId);
|
||||||
if (!session) return;
|
if (!session) return;
|
||||||
|
|
||||||
// 通知对端连接断开(但不删除会话)
|
// Notify peer of disconnection (but don't delete session)
|
||||||
const peer = userRole === 'creator' ? session.joiner : session.creator;
|
const peer = userRole === 'creator' ? session.joiner : session.creator;
|
||||||
if (peer && peer.ws.readyState === ws.OPEN) {
|
if (peer && peer.ws.readyState === ws.OPEN) {
|
||||||
peer.ws.send(JSON.stringify({
|
peer.ws.send(JSON.stringify({
|
||||||
@ -208,25 +231,25 @@ export const setupSignalingServer = (httpServer) => {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 只清理断开的用户,保留会话结构
|
// Only clear the disconnected user, keep session structure
|
||||||
if (userRole === 'creator') {
|
if (userRole === 'creator') {
|
||||||
console.log(`创建者断开连接: ${sessionId}`);
|
console.log(`Creator disconnected from session: ${sessionId}`);
|
||||||
session.creator = null;
|
session.creator = null;
|
||||||
} else {
|
} else {
|
||||||
console.log(`加入者断开连接: ${sessionId}`);
|
console.log(`Joiner disconnected from session: ${sessionId}`);
|
||||||
session.joiner = null;
|
session.joiner = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果双方都断开,才删除会话
|
// Only delete session if both parties are disconnected
|
||||||
if (!session.creator && !session.joiner) {
|
if (!session.creator && !session.joiner) {
|
||||||
sessions.delete(sessionId);
|
sessions.delete(sessionId);
|
||||||
console.log(`会话结束(双方都断开): ${sessionId}`);
|
console.log(`Session ended (both parties disconnected): ${sessionId}`);
|
||||||
} else {
|
} else {
|
||||||
console.log(`会话保留,等待重连: ${sessionId}`);
|
console.log(`Session retained, waiting for reconnection: ${sessionId}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(`${Green('[✓]')} WebSocket信令服务器启动成功`);
|
console.log(`${Green('[✓]')} WebSocket signaling server started successfully`);
|
||||||
return wss;
|
return wss;
|
||||||
};
|
};
|
||||||
|
Loading…
Reference in New Issue
Block a user