diff --git a/client/renderer/app.js b/client/renderer/app.js
index 974a3ff..561b0e2 100644
--- a/client/renderer/app.js
+++ b/client/renderer/app.js
@@ -4,6 +4,15 @@ const $$ = (sel) => document.querySelectorAll(sel);
let isConnected = false;
let currentServerUrl = '';
+let appSettings = {};
+
+// Load settings on startup
+(async () => {
+ appSettings = await window.funmc.getSettings();
+ if (appSettings.serverUrl) $('#server-url').value = appSettings.serverUrl;
+ if (appSettings.localPort) $('#join-local-port').value = appSettings.localPort;
+ showRecentServers();
+})();
// ===== Window Controls =====
$('#btn-min').addEventListener('click', () => window.funmc.minimize());
@@ -42,6 +51,11 @@ $('#btn-connect').addEventListener('click', async () => {
updateServerStatus(true);
showMsg('#connect-msg', '连接成功!', 'success');
showServerInfo(result.data);
+ // Save to recent servers and settings
+ await window.funmc.addRecentServer(url);
+ await window.funmc.setSettings({ serverUrl: url });
+ appSettings.serverUrl = url;
+ showRecentServers();
} else {
isConnected = false;
updateServerStatus(false);
@@ -125,13 +139,14 @@ async function loadRooms() {
`).join('');
}
-function quickJoin(roomId) {
+async function quickJoin(roomId) {
// Navigate to join page and fill in room ID
$$('.nav-item').forEach(n => n.classList.remove('active'));
document.querySelector('[data-page="join"]').classList.add('active');
$$('.page').forEach(p => p.classList.remove('active'));
$('#page-join').classList.add('active');
$('#join-room-id').value = roomId;
+ if (appSettings.localPort) $('#join-local-port').value = appSettings.localPort;
}
// ===== Host Page =====
@@ -255,6 +270,62 @@ document.querySelector('[data-page="rooms"]').addEventListener('click', () => {
if (isConnected) loadRooms();
});
+// ===== Settings Page =====
+document.querySelector('[data-page="settings"]').addEventListener('click', loadSettings);
+
+async function loadSettings() {
+ appSettings = await window.funmc.getSettings();
+ $('#settings-name').value = appSettings.playerName || '';
+ $('#settings-port').value = appSettings.localPort || 25566;
+ $('#settings-autoreconnect').checked = appSettings.autoReconnect !== false;
+ $('#settings-tray').checked = appSettings.minimizeToTray !== false;
+
+ const list = $('#settings-recent-list');
+ const recent = appSettings.recentServers || [];
+ if (recent.length === 0) {
+ list.innerHTML = '
暂无记录
';
+ } else {
+ list.innerHTML = recent.map(url => `
+
+ ${escapeHtml(url)}
+
+ `).join('');
+ }
+}
+
+$('#btn-save-settings').addEventListener('click', async () => {
+ const settings = {
+ playerName: $('#settings-name').value.trim() || 'Player',
+ localPort: parseInt($('#settings-port').value) || 25566,
+ autoReconnect: $('#settings-autoreconnect').checked,
+ minimizeToTray: $('#settings-tray').checked,
+ };
+ await window.funmc.setSettings(settings);
+ Object.assign(appSettings, settings);
+ $('#join-local-port').value = settings.localPort;
+ showMsg('#settings-msg', '设置已保存', 'success');
+ setTimeout(() => showMsg('#settings-msg', '', ''), 2000);
+});
+
+async function showRecentServers() {
+ const settings = await window.funmc.getSettings();
+ const recent = settings.recentServers || [];
+ const container = $('#recent-servers');
+ if (recent.length === 0) {
+ container.classList.add('hidden');
+ return;
+ }
+ container.classList.remove('hidden');
+ container.innerHTML = recent.map(url => `
+ ${escapeHtml(url)}
+ `).join('');
+ container.querySelectorAll('.recent-item').forEach(item => {
+ item.addEventListener('click', () => {
+ $('#server-url').value = item.dataset.url;
+ });
+ });
+}
+
// ===== Utilities =====
function showMsg(selector, text, type) {
const el = $(selector);
diff --git a/client/renderer/index.html b/client/renderer/index.html
index 90266d2..07ec59a 100644
--- a/client/renderer/index.html
+++ b/client/renderer/index.html
@@ -50,6 +50,9 @@
🚀 加入房间
+
+ ⚙️ 设置
+
ℹ️ 关于
@@ -67,6 +70,7 @@
@@ -182,6 +186,46 @@
+
+
+
关于 FunConnect
diff --git a/client/renderer/style.css b/client/renderer/style.css
index 891e88d..d9e224c 100644
--- a/client/renderer/style.css
+++ b/client/renderer/style.css
@@ -420,6 +420,57 @@ select.input { cursor: pointer; }
.step strong { font-size: 13px; display: block; margin-bottom: 3px; }
.step p { font-size: 12px; color: var(--text-dim); }
+/* Settings */
+.toggle-label {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ cursor: pointer;
+ font-size: 13px;
+}
+.toggle-label input[type="checkbox"] {
+ width: 18px;
+ height: 18px;
+ accent-color: var(--green);
+ cursor: pointer;
+}
+.recent-servers {
+ margin-top: 6px;
+ background: var(--bg-dark);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ max-height: 120px;
+ overflow-y: auto;
+}
+.recent-item {
+ padding: 8px 12px;
+ font-size: 12px;
+ color: var(--text-dim);
+ cursor: pointer;
+ transition: background 0.15s;
+ border-bottom: 1px solid var(--border);
+}
+.recent-item:last-child { border-bottom: none; }
+.recent-item:hover { background: rgba(76, 175, 80, 0.1); color: var(--text); }
+.recent-list {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ margin-top: 6px;
+}
+.recent-list-item {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ background: var(--bg-dark);
+ border-radius: 6px;
+ padding: 8px 12px;
+ font-size: 12px;
+ color: var(--text-dim);
+}
+.recent-list-item .url { flex: 1; }
+.recent-list-empty { font-size: 12px; color: #555; padding: 8px 0; }
+
/* Utility */
.hidden { display: none !important; }
diff --git a/client/src/main/api-client.ts b/client/src/main/api-client.ts
index ed9fc64..8e1e1b6 100644
--- a/client/src/main/api-client.ts
+++ b/client/src/main/api-client.ts
@@ -47,4 +47,14 @@ export class ApiClient {
const res = await this.http.get(`/rooms/${roomId}`);
return res.data;
}
+
+ async joinRoom(roomId: string, password?: string) {
+ const res = await this.http.post(`/rooms/${roomId}/join`, { password });
+ return res.data;
+ }
+
+ async getTraffic() {
+ const res = await this.http.get('/traffic');
+ return res.data;
+ }
}
diff --git a/client/src/main/index.ts b/client/src/main/index.ts
index b256cc0..6099afe 100644
--- a/client/src/main/index.ts
+++ b/client/src/main/index.ts
@@ -1,10 +1,23 @@
-import { app, BrowserWindow, ipcMain, dialog } from 'electron';
+import { app, BrowserWindow, ipcMain, dialog, Tray, Menu, nativeImage } from 'electron';
import * as path from 'path';
+import Store from 'electron-store';
import { RelayClient } from './relay-client';
import { LocalProxy } from './local-proxy';
import { ApiClient } from './api-client';
+const store = new Store({
+ defaults: {
+ serverUrl: 'http://localhost:3000',
+ playerName: 'Player',
+ localPort: 25566,
+ recentServers: [] as string[],
+ autoReconnect: true,
+ minimizeToTray: true,
+ }
+});
+
let mainWindow: BrowserWindow | null = null;
+let tray: Tray | null = null;
let relayClient: RelayClient | null = null;
let localProxy: LocalProxy | null = null;
let apiClient: ApiClient | null = null;
@@ -28,12 +41,33 @@ function createWindow() {
mainWindow.loadFile(path.join(__dirname, '../../renderer/index.html'));
+ mainWindow.on('close', (e) => {
+ if (store.get('minimizeToTray') && tray) {
+ e.preventDefault();
+ mainWindow?.hide();
+ }
+ });
+
mainWindow.on('closed', () => {
mainWindow = null;
cleanup();
});
}
+function createTray() {
+ const icon = nativeImage.createEmpty();
+ tray = new Tray(icon);
+ tray.setToolTip('FunConnect - Minecraft 联机客户端');
+ tray.setContextMenu(Menu.buildFromTemplate([
+ { label: '显示主窗口', click: () => { mainWindow?.show(); mainWindow?.focus(); } },
+ { type: 'separator' },
+ { label: '断开连接', click: () => cleanup() },
+ { type: 'separator' },
+ { label: '退出', click: () => { cleanup(); app.quit(); } },
+ ]));
+ tray.on('double-click', () => { mainWindow?.show(); mainWindow?.focus(); });
+}
+
function cleanup() {
if (localProxy) {
localProxy.stop();
@@ -47,9 +81,11 @@ function cleanup() {
app.whenReady().then(() => {
createWindow();
+ createTray();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
+ else mainWindow?.show();
});
});
@@ -171,3 +207,41 @@ ipcMain.handle('server:stats', async () => {
return { success: false, error: err.message };
}
});
+
+// ===== Settings =====
+ipcMain.handle('settings:get', () => {
+ return {
+ serverUrl: store.get('serverUrl'),
+ playerName: store.get('playerName'),
+ localPort: store.get('localPort'),
+ recentServers: store.get('recentServers'),
+ autoReconnect: store.get('autoReconnect'),
+ minimizeToTray: store.get('minimizeToTray'),
+ };
+});
+
+ipcMain.handle('settings:set', (_event, settings: Record) => {
+ for (const [key, value] of Object.entries(settings)) {
+ store.set(key, value);
+ }
+ return { success: true };
+});
+
+ipcMain.handle('settings:addRecentServer', (_event, url: string) => {
+ const recent = store.get('recentServers') as string[];
+ const filtered = recent.filter((s: string) => s !== url);
+ filtered.unshift(url);
+ store.set('recentServers', filtered.slice(0, 10));
+ return { success: true };
+});
+
+// ===== Room password verification =====
+ipcMain.handle('rooms:verify', async (_event, opts: { roomId: string; password?: string }) => {
+ if (!apiClient) return { success: false, error: '未连接服务器' };
+ try {
+ const data = await apiClient.joinRoom(opts.roomId, opts.password);
+ return { success: true, data };
+ } catch (err: any) {
+ return { success: false, error: err.response?.data?.error || err.message };
+ }
+});
diff --git a/client/src/main/preload.ts b/client/src/main/preload.ts
index 42bb849..8bb1502 100644
--- a/client/src/main/preload.ts
+++ b/client/src/main/preload.ts
@@ -18,6 +18,14 @@ contextBridge.exposeInMainWorld('funmc', {
hostRoom: (opts: any) => ipcRenderer.invoke('rooms:host', opts),
disconnect: () => ipcRenderer.invoke('relay:disconnect'),
+ // Room verification
+ verifyRoom: (opts: any) => ipcRenderer.invoke('rooms:verify', opts),
+
+ // Settings
+ getSettings: () => ipcRenderer.invoke('settings:get'),
+ setSettings: (settings: any) => ipcRenderer.invoke('settings:set', settings),
+ addRecentServer: (url: string) => ipcRenderer.invoke('settings:addRecentServer', url),
+
// Events from main
onRelayStatus: (callback: (data: any) => void) => {
ipcRenderer.on('relay:status', (_event, data) => callback(data));
diff --git a/server/src/api.ts b/server/src/api.ts
index 1afe248..83c2972 100644
--- a/server/src/api.ts
+++ b/server/src/api.ts
@@ -5,12 +5,31 @@ import { RelayEngine } from './relay';
import config from './config';
import logger from './logger';
+function formatBytes(bytes: number): string {
+ if (bytes === 0) return '0 B';
+ const k = 1024;
+ const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
+}
+
+function authMiddleware(req: Request, res: Response, next: any) {
+ if (!config.secret) return next();
+ const token = req.headers['x-auth-token'] || req.query.token;
+ if (token === config.secret) return next();
+ // Allow public read endpoints
+ const publicPaths = ['/health', '/rooms', '/stats'];
+ if (req.method === 'GET' && publicPaths.some(p => req.path.startsWith(p))) return next();
+ res.status(401).json({ error: '认证失败,请提供有效的token' });
+}
+
export function createApiRouter(
roomManager: RoomManager,
nodeManager: NodeManager,
relayEngine: RelayEngine
): Router {
const router = Router();
+ router.use(authMiddleware);
// ===== Health & Status =====
router.get('/health', (_req: Request, res: Response) => {
@@ -84,7 +103,49 @@ export function createApiRouter(
res.status(404).json({ error: '房间不存在' });
return;
}
- res.json({ room: room.toInfo() });
+ res.json({ room: room.toInfo(), players: room.getPlayerList() });
+ });
+
+ // Join room with password verification
+ router.post('/rooms/:roomId/join', (req: Request, res: Response) => {
+ const room = roomManager.getRoom(req.params.roomId);
+ if (!room) {
+ res.status(404).json({ error: '房间不存在' });
+ return;
+ }
+ if (room.isFull) {
+ res.status(403).json({ error: '房间已满' });
+ return;
+ }
+ const { password } = req.body;
+ if (!room.checkPassword(password)) {
+ res.status(403).json({ error: '房间密码错误' });
+ return;
+ }
+ res.json({
+ allowed: true,
+ room: room.toInfo(),
+ connectInfo: {
+ host: config.isMaster ? 'MASTER_HOST' : config.nodeName,
+ port: config.port,
+ roomId: room.id,
+ },
+ });
+ });
+
+ // Kick player from room
+ router.post('/rooms/:roomId/kick/:playerId', (req: Request, res: Response) => {
+ const room = roomManager.getRoom(req.params.roomId);
+ if (!room) {
+ res.status(404).json({ error: '房间不存在' });
+ return;
+ }
+ const kicked = room.kickPlayer(req.params.playerId, req.body.reason);
+ if (!kicked) {
+ res.status(404).json({ error: '玩家不存在' });
+ return;
+ }
+ res.json({ message: '玩家已踢出' });
});
router.delete('/rooms/:roomId', (req: Request, res: Response) => {
@@ -164,6 +225,18 @@ export function createApiRouter(
res.json({ message: '节点已移除' });
});
+ // Traffic stats
+ router.get('/traffic', (_req: Request, res: Response) => {
+ const traffic = roomManager.getTrafficStats();
+ res.json({
+ ...traffic,
+ rooms: roomManager.getRoomCount(),
+ players: roomManager.getTotalPlayers(),
+ formattedIn: formatBytes(traffic.totalBytesIn),
+ formattedOut: formatBytes(traffic.totalBytesOut),
+ });
+ });
+
router.get('/nodes/best', (_req: Request, res: Response) => {
if (!config.isMaster) {
res.status(403).json({ error: '仅主节点可查询最佳节点' });
diff --git a/server/src/index.ts b/server/src/index.ts
index 43d65b9..8d3a0cb 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -58,6 +58,9 @@ async function main() {
await relayEngine.start(config.port);
+ // Start room expiry cleanup (every 5 minutes, 30 min idle timeout)
+ roomManager.startCleanupTimer();
+
if (!config.isMaster && config.masterUrl) {
await registerWithMaster();
startHeartbeat(roomManager);
diff --git a/server/src/room.ts b/server/src/room.ts
index 7ea952f..da68a4e 100644
--- a/server/src/room.ts
+++ b/server/src/room.ts
@@ -37,6 +37,9 @@ export class Room {
public password?: string;
public nodeId: string;
public createdAt: Date;
+ public lastActivity: Date;
+ public bytesIn: number = 0;
+ public bytesOut: number = 0;
public players: Map = new Map();
private playerSockets: Map = new Map();
@@ -61,6 +64,37 @@ export class Room {
this.nodeId = options.nodeId;
this.password = options.password;
this.createdAt = new Date();
+ this.lastActivity = new Date();
+ }
+
+ checkPassword(pwd?: string): boolean {
+ if (!this.password) return true;
+ return this.password === pwd;
+ }
+
+ touch(): void {
+ this.lastActivity = new Date();
+ }
+
+ addTraffic(bytesIn: number, bytesOut: number): void {
+ this.bytesIn += bytesIn;
+ this.bytesOut += bytesOut;
+ this.touch();
+ }
+
+ kickPlayer(playerId: string, reason?: string): boolean {
+ const player = this.players.get(playerId);
+ if (!player) return false;
+ logger.info(`Player ${player.name} kicked from room ${this.name}: ${reason || 'no reason'}`);
+ try { player.socket.destroy(); } catch (e) { /* ignore */ }
+ this.players.delete(playerId);
+ this.playerSockets.delete(playerId);
+ return true;
+ }
+
+ isExpired(maxIdleMs: number): boolean {
+ if (this.currentPlayers > 0) return false;
+ return Date.now() - this.lastActivity.getTime() > maxIdleMs;
}
get currentPlayers(): number {
@@ -93,6 +127,14 @@ export class Room {
}
}
+ getPlayerList(): { id: string; name: string; joinedAt: Date }[] {
+ return Array.from(this.players.values()).map(p => ({
+ id: p.id,
+ name: p.name,
+ joinedAt: p.joinedAt,
+ }));
+ }
+
toInfo(): RoomInfo {
return {
id: this.id,
@@ -184,4 +226,36 @@ export class RoomManager {
}
return total;
}
+
+ getTrafficStats(): { totalBytesIn: number; totalBytesOut: number } {
+ let totalBytesIn = 0;
+ let totalBytesOut = 0;
+ for (const [, room] of this.rooms) {
+ totalBytesIn += room.bytesIn;
+ totalBytesOut += room.bytesOut;
+ }
+ return { totalBytesIn, totalBytesOut };
+ }
+
+ cleanupExpiredRooms(maxIdleMs: number = 30 * 60 * 1000): number {
+ let cleaned = 0;
+ for (const [id, room] of this.rooms) {
+ if (room.isExpired(maxIdleMs)) {
+ logger.info(`Room ${room.name} (${id}) expired, cleaning up`);
+ room.destroy();
+ this.rooms.delete(id);
+ cleaned++;
+ }
+ }
+ return cleaned;
+ }
+
+ startCleanupTimer(intervalMs: number = 5 * 60 * 1000, maxIdleMs: number = 30 * 60 * 1000): void {
+ setInterval(() => {
+ const cleaned = this.cleanupExpiredRooms(maxIdleMs);
+ if (cleaned > 0) {
+ logger.info(`Cleaned up ${cleaned} expired rooms`);
+ }
+ }, intervalMs);
+ }
}