@wsl233/dsh-gomoku 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lan-server.js ADDED
@@ -0,0 +1,765 @@
1
+ /**
2
+ * dsh-gomoku — LAN server.
3
+ *
4
+ * Zero npm dependencies:
5
+ * - a small RFC 6455 WebSocket server (same approach as the standalone web
6
+ * version of this game);
7
+ * - a vendored MIT QR encoder (`vendor/qrcode.mjs`);
8
+ * - an authoritative, in-memory room per 4-digit code.
9
+ *
10
+ * The server is started by the DSH host half. It also serves a small join page
11
+ * so that another computer on the same LAN can open a normal browser tab.
12
+ */
13
+
14
+ import http from 'node:http';
15
+ import { readFile } from 'node:fs/promises';
16
+ import { createHash } from 'node:crypto';
17
+ import { existsSync } from 'node:fs';
18
+ import { networkInterfaces } from 'node:os';
19
+ import { extname, resolve, sep } from 'node:path';
20
+ import QRCode from './vendor/qrcode.mjs';
21
+
22
+ const MAX_MESSAGE = 16 * 1024;
23
+ const MAX_FRAGMENT = 64 * 1024;
24
+ const MAX_ROOMS = 300;
25
+ const ROOM_IDLE_MS = 2 * 60 * 60 * 1000;
26
+ const PROTOCOL = 1;
27
+ const PREFERRED_PORTS = [8790, 8791, 8792, 8793, 8794, 8795, 8796, 8797, 8798, 8799];
28
+
29
+ const SIZE = 19;
30
+ const EMPTY = 0;
31
+ const BLACK = 1;
32
+ const WHITE = 2;
33
+
34
+ const MIME = {
35
+ '.html': 'text/html; charset=utf-8',
36
+ '.css': 'text/css; charset=utf-8',
37
+ '.js': 'text/javascript; charset=utf-8',
38
+ '.mjs': 'text/javascript; charset=utf-8',
39
+ '.json': 'application/json; charset=utf-8',
40
+ '.png': 'image/png',
41
+ '.svg': 'image/svg+xml',
42
+ };
43
+
44
+ function nowMs() {
45
+ return Date.now();
46
+ }
47
+
48
+ function lanAddresses() {
49
+ const out = [];
50
+ const nets = networkInterfaces();
51
+ for (const name of Object.keys(nets)) {
52
+ for (const item of nets[name] || []) {
53
+ const isV4 = item.family === 'IPv4' || item.family === 4;
54
+ if (!isV4 || item.internal || item.address.startsWith('169.254.')) continue;
55
+ out.push({ name, address: item.address });
56
+ }
57
+ }
58
+ return out;
59
+ }
60
+
61
+ function nonLocalAddress() {
62
+ const list = lanAddresses();
63
+ const preferred = list.find((item) => /^192\.168\./.test(item.address))
64
+ || list.find((item) => /^10\./.test(item.address))
65
+ || list.find((item) => /^172\.(1[6-9]|2\d|3[01])\./.test(item.address))
66
+ || list[0];
67
+ return preferred ? preferred.address : '127.0.0.1';
68
+ }
69
+
70
+ function wsAccept(key) {
71
+ return createHash('sha1')
72
+ .update(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
73
+ .digest('base64');
74
+ }
75
+
76
+ function encodeFrame(opcode, payload) {
77
+ const len = payload.length;
78
+ let header;
79
+ if (len < 126) {
80
+ header = Buffer.alloc(2);
81
+ header[1] = len;
82
+ } else if (len < 65536) {
83
+ header = Buffer.alloc(4);
84
+ header[1] = 126;
85
+ header.writeUInt16BE(len, 2);
86
+ } else {
87
+ header = Buffer.alloc(10);
88
+ header[1] = 127;
89
+ header.writeBigUInt64BE(BigInt(len), 2);
90
+ }
91
+ header[0] = 0x80 | opcode;
92
+ return Buffer.concat([header, payload]);
93
+ }
94
+
95
+ class Client {
96
+ constructor(socket) {
97
+ this.socket = socket;
98
+ this.buffer = Buffer.alloc(0);
99
+ this.fragments = [];
100
+ this.fragmentBytes = 0;
101
+ this.fragmentOpcode = 0;
102
+ this.closed = false;
103
+ this.alive = true;
104
+ this.room = null;
105
+ this.color = 0;
106
+ this.windowStart = nowMs();
107
+ this.windowCount = 0;
108
+
109
+ socket.on('data', (chunk) => this.feed(chunk));
110
+ socket.on('error', () => this.teardown());
111
+ socket.on('close', () => this.teardown());
112
+ socket.setNoDelay(true);
113
+ }
114
+
115
+ feed(chunk) {
116
+ if (this.closed) return;
117
+ this.alive = true;
118
+ this.buffer = this.buffer.length ? Buffer.concat([this.buffer, chunk]) : chunk;
119
+ if (this.buffer.length > MAX_FRAGMENT + 14) return this.close(1009, 'message too large');
120
+ while (this.buffer.length >= 2) {
121
+ const first = this.buffer[0];
122
+ const second = this.buffer[1];
123
+ const fin = (first & 0x80) !== 0;
124
+ const opcode = first & 0x0f;
125
+ const masked = (second & 0x80) !== 0;
126
+ let len = second & 0x7f;
127
+ let offset = 2;
128
+ if (!masked) return this.close(1002, 'client frames must be masked');
129
+ if (len === 126) {
130
+ if (this.buffer.length < 4) return;
131
+ len = this.buffer.readUInt16BE(2);
132
+ offset = 4;
133
+ } else if (len === 127) {
134
+ if (this.buffer.length < 10) return;
135
+ const high = this.buffer.readUInt32BE(2);
136
+ const low = this.buffer.readUInt32BE(6);
137
+ if (high !== 0 || low > MAX_FRAGMENT) return this.close(1009, 'message too large');
138
+ len = low;
139
+ offset = 10;
140
+ }
141
+ if (this.buffer.length < offset + 4 + len) return;
142
+ const mask = this.buffer.slice(offset, offset + 4);
143
+ offset += 4;
144
+ const payload = Buffer.from(this.buffer.slice(offset, offset + len));
145
+ for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i & 3];
146
+ this.buffer = this.buffer.slice(offset + len);
147
+
148
+ if (opcode >= 0x8) {
149
+ if (!fin || len > 125) return this.close(1002, 'invalid control frame');
150
+ if (opcode === 0x8) {
151
+ this.close(1000, '');
152
+ return;
153
+ }
154
+ if (opcode === 0x9) this.sendFrame(0xA, payload);
155
+ else if (opcode !== 0xA) return this.close(1002, 'unknown opcode');
156
+ continue;
157
+ }
158
+
159
+ if (opcode === 0x1 || opcode === 0x2) {
160
+ if (this.fragmentOpcode) return this.close(1002, 'nested fragment');
161
+ if (opcode === 0x2) return this.close(1003, 'binary not supported');
162
+ if (fin) this.handleMessage(payload.toString('utf8'));
163
+ else {
164
+ this.fragmentOpcode = opcode;
165
+ this.fragments = [payload];
166
+ this.fragmentBytes = payload.length;
167
+ }
168
+ } else if (opcode === 0x0) {
169
+ if (!this.fragmentOpcode) return this.close(1002, 'unexpected continuation');
170
+ this.fragments.push(payload);
171
+ this.fragmentBytes += payload.length;
172
+ if (this.fragmentBytes > MAX_MESSAGE) return this.close(1009, 'message too large');
173
+ if (fin) {
174
+ const whole = Buffer.concat(this.fragments);
175
+ this.fragmentOpcode = 0;
176
+ this.fragments = [];
177
+ this.fragmentBytes = 0;
178
+ this.handleMessage(whole.toString('utf8'));
179
+ }
180
+ } else {
181
+ return this.close(1002, 'unknown opcode');
182
+ }
183
+ }
184
+ }
185
+
186
+ handleMessage(text) {
187
+ if (this.closed) return;
188
+ const now = nowMs();
189
+ if (now - this.windowStart > 1000) {
190
+ this.windowStart = now;
191
+ this.windowCount = 0;
192
+ }
193
+ this.windowCount++;
194
+ if (this.windowCount > 120) return this.close(1008, 'too many messages');
195
+ let message;
196
+ try {
197
+ message = JSON.parse(text);
198
+ } catch {
199
+ return this.error('bad-message', '消息不是合法 JSON');
200
+ }
201
+ if (!message || typeof message !== 'object' || typeof message.type !== 'string') {
202
+ return this.error('bad-message', '消息缺少 type');
203
+ }
204
+ this.onMessage(message);
205
+ }
206
+
207
+ sendFrame(opcode, payload) {
208
+ if (this.closed || this.socket.destroyed) return;
209
+ try {
210
+ this.socket.write(encodeFrame(opcode, payload));
211
+ } catch {
212
+ this.teardown();
213
+ }
214
+ }
215
+
216
+ send(object) {
217
+ this.sendFrame(0x1, Buffer.from(JSON.stringify(object), 'utf8'));
218
+ }
219
+
220
+ error(code, message) {
221
+ this.send({ type: 'error', protocol: PROTOCOL, code, message });
222
+ }
223
+
224
+ ping() {
225
+ this.sendFrame(0x9, Buffer.alloc(0));
226
+ }
227
+
228
+ close(code, reason) {
229
+ if (this.closed) return;
230
+ this.closed = true;
231
+ if (!this.socket.destroyed) {
232
+ const reasonBuf = Buffer.from(String(reason || ''), 'utf8');
233
+ const payload = Buffer.alloc(2 + reasonBuf.length);
234
+ payload.writeUInt16BE(code, 0);
235
+ reasonBuf.copy(payload, 2);
236
+ try {
237
+ this.socket.write(encodeFrame(0x8, payload));
238
+ } catch {
239
+ // ignore
240
+ }
241
+ this.socket.end();
242
+ }
243
+ }
244
+
245
+ terminate() {
246
+ if (this.socket.destroyed) return;
247
+ this.closed = true;
248
+ this.socket.destroy();
249
+ }
250
+
251
+ teardown() {
252
+ if (this.closed && this.socket.destroyed) {
253
+ // still allow room cleanup once
254
+ }
255
+ this.closed = true;
256
+ clients.delete(this);
257
+ handleDisconnect(this);
258
+ }
259
+ }
260
+
261
+ const clients = new Set();
262
+ const rooms = new Map();
263
+
264
+ function emptyBoard() {
265
+ return new Int8Array(SIZE * SIZE);
266
+ }
267
+
268
+ function idx(x, y) {
269
+ return y * SIZE + x;
270
+ }
271
+
272
+ function findWin(board, x, y, color) {
273
+ const dirs = [[1, 0], [0, 1], [1, 1], [1, -1]];
274
+ for (const [dx, dy] of dirs) {
275
+ let back = 0;
276
+ let fx = x - dx;
277
+ let fy = y - dy;
278
+ while (fx >= 0 && fy >= 0 && fx < SIZE && fy < SIZE && board[idx(fx, fy)] === color) {
279
+ back++;
280
+ fx -= dx;
281
+ fy -= dy;
282
+ }
283
+ let forward = 0;
284
+ fx = x + dx;
285
+ fy = y + dy;
286
+ while (fx >= 0 && fy >= 0 && fx < SIZE && fy < SIZE && board[idx(fx, fy)] === color) {
287
+ forward++;
288
+ fx += dx;
289
+ fy += dy;
290
+ }
291
+ if (back + forward + 1 >= 5) {
292
+ const line = [];
293
+ for (let i = -back; i <= forward; i++) line.push({ x: x + dx * i, y: y + dy * i });
294
+ return line;
295
+ }
296
+ }
297
+ return null;
298
+ }
299
+
300
+ function freshGame() {
301
+ return { board: emptyBoard(), moves: [], turn: BLACK, winner: EMPTY, winLine: null };
302
+ }
303
+
304
+ function roomState(room, youColor) {
305
+ return {
306
+ type: 'state',
307
+ protocol: PROTOCOL,
308
+ room: room.code,
309
+ status: room.status,
310
+ youColor,
311
+ players: { black: !!room.players[1], white: !!room.players[2] },
312
+ names: {
313
+ black: (room.names && room.names[1]) || '',
314
+ white: (room.names && room.names[2]) || '',
315
+ },
316
+ board: Array.from(room.game.board),
317
+ moves: room.game.moves.map((m) => ({ x: m.x, y: m.y, color: m.color })),
318
+ turn: room.game.turn,
319
+ winner: room.game.winner,
320
+ winLine: room.game.winLine,
321
+ round: room.round,
322
+ };
323
+ }
324
+
325
+ function broadcast(room) {
326
+ room.updatedAt = nowMs();
327
+ for (const color of [BLACK, WHITE]) {
328
+ const player = room.players[color];
329
+ if (!player || player.closed) continue;
330
+ player.send(roomState(room, color));
331
+ }
332
+ }
333
+
334
+ function attach(client, room, color) {
335
+ const old = room.players[color];
336
+ if (old && old !== client && !old.closed) old.close(4001, '在另一处加入房间');
337
+ client.room = room;
338
+ client.color = color;
339
+ room.players[color] = client;
340
+ room.updatedAt = nowMs();
341
+ }
342
+
343
+ function closeRoom(room) {
344
+ if (!room || !rooms.has(room.code)) return;
345
+ rooms.delete(room.code);
346
+ for (const color of [BLACK, WHITE]) {
347
+ const player = room.players[color];
348
+ if (!player) continue;
349
+ player.room = null;
350
+ if (!player.closed) player.close(1000, '房间已关闭');
351
+ }
352
+ }
353
+
354
+ function handleDisconnect(client) {
355
+ const room = client.room;
356
+ if (!room || !rooms.has(room.code)) return;
357
+ if (room.players[client.color] === client) {
358
+ room.players[client.color] = null;
359
+ if (room.names) room.names[client.color] = '';
360
+ }
361
+ if (!room.players[1] && !room.players[2]) {
362
+ closeRoom(room);
363
+ return;
364
+ }
365
+ if (room.status === 'playing') room.status = 'waiting';
366
+ broadcast(room);
367
+ }
368
+
369
+ function sendError(client, code, message) {
370
+ client.error(code, message);
371
+ }
372
+
373
+ function handleJoin(client, role, code) {
374
+ if (client.room) return sendError(client, 'already-in-room', '你已经在房间中');
375
+ if (!/^\d{4}$/.test(code)) return sendError(client, 'bad-room', '房间号应为 4 位数字');
376
+ if (role === 'host') {
377
+ let room = rooms.get(code);
378
+ if (!room) {
379
+ if (rooms.size >= MAX_ROOMS) return sendError(client, 'server-busy', '房间数量已达上限');
380
+ room = {
381
+ code,
382
+ game: freshGame(),
383
+ players: { 1: null, 2: null },
384
+ names: { 1: '', 2: '' },
385
+ status: 'waiting',
386
+ round: 1,
387
+ updatedAt: nowMs(),
388
+ };
389
+ rooms.set(code, room);
390
+ } else if (room.players[1]) {
391
+ return sendError(client, 'room-taken', '这个房间号已被占用,请重新创建');
392
+ }
393
+ attach(client, room, BLACK);
394
+ client.send({
395
+ type: 'welcome',
396
+ protocol: PROTOCOL,
397
+ room: code,
398
+ color: BLACK,
399
+ role: 'host',
400
+ });
401
+ broadcast(room);
402
+ return;
403
+ }
404
+
405
+ if (role !== 'guest') return sendError(client, 'bad-role', '连接角色无效');
406
+ const room = rooms.get(code);
407
+ if (!room) return sendError(client, 'room-not-found', '房间不存在或已结束');
408
+ if (room.players[2]) return sendError(client, 'room-full', '房间已满');
409
+ attach(client, room, WHITE);
410
+ room.status = room.game.winner ? 'over' : 'playing';
411
+ client.send({
412
+ type: 'welcome',
413
+ protocol: PROTOCOL,
414
+ room: code,
415
+ color: WHITE,
416
+ role: 'guest',
417
+ });
418
+ broadcast(room);
419
+ room.players[1]?.send({ type: 'notice', protocol: PROTOCOL, text: '对手已加入,黑方先行。' });
420
+ }
421
+
422
+ function handleMove(client, message) {
423
+ const room = client.room;
424
+ if (!room) return sendError(client, 'not-in-room', '你还没有加入房间');
425
+ if (room.status !== 'playing') return sendError(client, 'not-playing', '当前不能落子');
426
+ if (room.players[client.color] !== client) return sendError(client, 'bad-session', '连接状态异常');
427
+ if (room.game.turn !== client.color) return sendError(client, 'not-your-turn', '还没轮到你落子');
428
+ const x = Number(message.x);
429
+ const y = Number(message.y);
430
+ if (!Number.isInteger(x) || !Number.isInteger(y) || x < 0 || x >= SIZE || y < 0 || y >= SIZE) {
431
+ return sendError(client, 'bad-move', '坐标不合法');
432
+ }
433
+ if (room.game.board[idx(x, y)] !== EMPTY) return sendError(client, 'illegal-move', '这个位置不能落子');
434
+ room.game.board[idx(x, y)] = client.color;
435
+ room.game.moves.push({ x, y, color: client.color });
436
+ const win = findWin(room.game.board, x, y, client.color);
437
+ if (win) {
438
+ room.game.winner = client.color;
439
+ room.game.winLine = win;
440
+ room.status = 'over';
441
+ } else if (room.game.moves.length >= SIZE * SIZE) {
442
+ room.game.winner = 3;
443
+ room.status = 'over';
444
+ } else {
445
+ room.game.turn = 3 - client.color;
446
+ }
447
+ broadcast(room);
448
+ }
449
+
450
+ function handleName(client, message) {
451
+ const room = client.room;
452
+ if (!room) return sendError(client, 'not-in-room', '你还没有加入房间');
453
+ if (!room.names) room.names = { 1: '', 2: '' };
454
+ const name = String(message.name || '')
455
+ .replace(/\s+/g, ' ')
456
+ .trim()
457
+ .slice(0, 12);
458
+ room.names[client.color] = name || (client.color === BLACK ? '房主' : '挑战者');
459
+ broadcast(room);
460
+ }
461
+
462
+ function handleReset(client) {
463
+ const room = client.room;
464
+ if (!room) return sendError(client, 'not-in-room', '你还没有加入房间');
465
+ if (room.status === 'playing' && room.game.moves.length > 0) {
466
+ return sendError(client, 'game-running', '对局进行中,暂不能重新开始');
467
+ }
468
+ room.game = freshGame();
469
+ room.round++;
470
+ room.status = room.players[2] ? 'playing' : 'waiting';
471
+ broadcast(room);
472
+ for (const color of [BLACK, WHITE]) {
473
+ const player = room.players[color];
474
+ if (player) player.send({ type: 'notice', protocol: PROTOCOL, text: '新一局开始。' });
475
+ }
476
+ }
477
+
478
+ function handleClientMessage(client, message) {
479
+ switch (message.type) {
480
+ case 'move':
481
+ return handleMove(client, message);
482
+ case 'name':
483
+ return handleName(client, message);
484
+ case 'reset':
485
+ return handleReset(client);
486
+ case 'leave':
487
+ return client.close(1000, '已离开');
488
+ case 'ping':
489
+ return client.send({ type: 'pong', protocol: PROTOCOL });
490
+ default:
491
+ return sendError(client, 'unknown-type', '未知消息类型');
492
+ }
493
+ }
494
+
495
+ Client.prototype.onMessage = function onMessage(message) {
496
+ handleClientMessage(this, message);
497
+ };
498
+
499
+ function qrSvg(text) {
500
+ const qr = QRCode(0, 'M');
501
+ qr.addData(String(text));
502
+ qr.make();
503
+ const count = qr.getModuleCount();
504
+ const cell = 4;
505
+ const margin = 4;
506
+ const size = (count + margin * 2) * cell;
507
+ const parts = [
508
+ '<?xml version="1.0" encoding="UTF-8"?>',
509
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" role="img" aria-label="加入房间二维码">`,
510
+ `<rect width="${size}" height="${size}" fill="#ffffff"/>`,
511
+ '<g fill="#1f2937">',
512
+ ];
513
+ for (let row = 0; row < count; row++) {
514
+ for (let col = 0; col < count; col++) {
515
+ if (!qr.isDark(row, col)) continue;
516
+ parts.push(
517
+ `<rect x="${(col + margin) * cell}" y="${(row + margin) * cell}" width="${cell}" height="${cell}"/>`
518
+ );
519
+ }
520
+ }
521
+ parts.push('</g></svg>');
522
+ return parts.join('');
523
+ }
524
+
525
+ async function serveFile(res, file, method) {
526
+ let content;
527
+ try {
528
+ content = await readFile(file);
529
+ } catch {
530
+ res.statusCode = 404;
531
+ res.end('Not found');
532
+ return;
533
+ }
534
+ res.statusCode = 200;
535
+ res.setHeader('Content-Type', MIME[extname(file).toLowerCase()] || 'application/octet-stream');
536
+ res.setHeader('Cache-Control', 'no-store');
537
+ res.setHeader('X-Content-Type-Options', 'nosniff');
538
+ if (method === 'HEAD') {
539
+ res.end();
540
+ return;
541
+ }
542
+ res.end(content);
543
+ }
544
+
545
+ function createHandler({ root }) {
546
+ const uiDir = resolve(root, 'ui');
547
+ const assetsDir = resolve(root, 'assets');
548
+
549
+ return function handle(req, res) {
550
+ const method = req.method || 'GET';
551
+ if (method !== 'GET' && method !== 'HEAD') {
552
+ res.statusCode = 405;
553
+ res.setHeader('Allow', 'GET, HEAD');
554
+ res.end();
555
+ return;
556
+ }
557
+ let pathname;
558
+ let url;
559
+ try {
560
+ url = new URL(String(req.url || '/'), 'http://127.0.0.1');
561
+ pathname = decodeURIComponent(url.pathname);
562
+ } catch {
563
+ res.statusCode = 400;
564
+ res.end('Bad request');
565
+ return;
566
+ }
567
+
568
+ if (pathname === '/dsh-gomoku/lan/info') {
569
+ const address = nonLocalAddress();
570
+ const origin = `http://${address}:${req.socket.localPort}`;
571
+ res.statusCode = 200;
572
+ res.setHeader('Content-Type', MIME['.json']);
573
+ res.setHeader('Cache-Control', 'no-store');
574
+ res.end(JSON.stringify({
575
+ ok: true,
576
+ wsOrigin: origin.replace(/^http/, 'ws'),
577
+ linkBase: `${origin}/lan.html`,
578
+ origin,
579
+ }));
580
+ return;
581
+ }
582
+
583
+ if (pathname === '/info' || pathname === '/health') {
584
+ res.statusCode = 200;
585
+ res.setHeader('Content-Type', MIME['.json']);
586
+ res.setHeader('Cache-Control', 'no-store');
587
+ res.end(JSON.stringify({ ok: true, name: 'dsh-gomoku', size: SIZE }));
588
+ return;
589
+ }
590
+
591
+ if (pathname === '/qr.svg') {
592
+ const text = url.searchParams.get('text') || '';
593
+ if (!text || text.length > 900) {
594
+ res.statusCode = 400;
595
+ res.end('Bad qr text');
596
+ return;
597
+ }
598
+ try {
599
+ const svg = qrSvg(text);
600
+ res.statusCode = 200;
601
+ res.setHeader('Content-Type', MIME['.svg']);
602
+ res.setHeader('Cache-Control', 'no-store');
603
+ res.end(svg);
604
+ } catch {
605
+ res.statusCode = 500;
606
+ res.end('QR error');
607
+ }
608
+ return;
609
+ }
610
+
611
+ if (pathname === '/' || pathname === '/lan.html' || pathname === '/index.html') {
612
+ serveFile(res, resolve(uiDir, 'lan.html'), method);
613
+ return;
614
+ }
615
+
616
+ let base = null;
617
+ let relative = '';
618
+ if (pathname.startsWith('/ui/')) {
619
+ base = uiDir;
620
+ relative = pathname.slice('/ui/'.length);
621
+ } else if (pathname.startsWith('/assets/')) {
622
+ base = assetsDir;
623
+ relative = pathname.slice('/assets/'.length);
624
+ }
625
+ if (!base || !relative) {
626
+ res.statusCode = 404;
627
+ res.end('Not found');
628
+ return;
629
+ }
630
+ const file = resolve(base, relative);
631
+ if (!file.startsWith(base + sep) || relative.includes('\0')) {
632
+ res.statusCode = 404;
633
+ res.end('Not found');
634
+ return;
635
+ }
636
+ serveFile(res, file, method);
637
+ };
638
+ }
639
+
640
+ function promiseListen(server, port) {
641
+ return new Promise((resolveListen, reject) => {
642
+ const onError = (error) => {
643
+ server.removeListener('listening', onListening);
644
+ reject(error);
645
+ };
646
+ const onListening = () => {
647
+ server.removeListener('error', onError);
648
+ resolveListen();
649
+ };
650
+ server.once('error', onError);
651
+ server.once('listening', onListening);
652
+ server.listen(port, '0.0.0.0');
653
+ });
654
+ }
655
+
656
+ /**
657
+ * Start the LAN server. Resolves to a handle used by the DSH host routes.
658
+ * @param {{root?: string, ports?: number[]}} options
659
+ */
660
+ export async function startLanServer(options = {}) {
661
+ const root = options.root || resolve('.');
662
+ const ports = options.ports || PREFERRED_PORTS;
663
+ const server = http.createServer(createHandler({ root }));
664
+ server.on('clientError', (err, socket) => {
665
+ if (socket.writable) socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
666
+ });
667
+
668
+ server.on('upgrade', (req, socket) => {
669
+ let url;
670
+ try {
671
+ url = new URL(req.url, 'http://127.0.0.1');
672
+ } catch {
673
+ socket.destroy();
674
+ return;
675
+ }
676
+ if (url.pathname !== '/ws') {
677
+ socket.write('HTTP/1.1 404 Not Found\r\n\r\n');
678
+ socket.destroy();
679
+ return;
680
+ }
681
+ const key = req.headers['sec-websocket-key'];
682
+ const version = req.headers['sec-websocket-version'];
683
+ if ((req.headers.upgrade || '').toLowerCase() !== 'websocket' || !key || version !== '13') {
684
+ socket.write('HTTP/1.1 400 Bad Request\r\n\r\n');
685
+ socket.destroy();
686
+ return;
687
+ }
688
+ const room = url.searchParams.get('room') || '';
689
+ const role = url.searchParams.get('role') || '';
690
+ socket.write(
691
+ 'HTTP/1.1 101 Switching Protocols\r\n' +
692
+ 'Upgrade: websocket\r\n' +
693
+ 'Connection: Upgrade\r\n' +
694
+ 'Sec-WebSocket-Accept: ' + wsAccept(key) + '\r\n\r\n'
695
+ );
696
+ const client = new Client(socket);
697
+ clients.add(client);
698
+ handleJoin(client, role, room);
699
+ });
700
+
701
+ let port = 0;
702
+ let lastError = null;
703
+ for (const candidate of ports) {
704
+ try {
705
+ await promiseListen(server, candidate);
706
+ port = candidate;
707
+ break;
708
+ } catch (error) {
709
+ lastError = error;
710
+ if (error && error.code !== 'EADDRINUSE') break;
711
+ }
712
+ }
713
+ if (!port) {
714
+ server.close();
715
+ throw lastError || new Error('没有可用的局域网端口');
716
+ }
717
+
718
+ const address = nonLocalAddress();
719
+ const origin = `http://${address}:${port}`;
720
+ const wsOrigin = `ws://${address}:${port}`;
721
+ const idleTimer = setInterval(() => {
722
+ const now = nowMs();
723
+ for (const room of rooms.values()) {
724
+ if (now - room.updatedAt > ROOM_IDLE_MS) closeRoom(room);
725
+ }
726
+ }, 5 * 60 * 1000);
727
+ idleTimer.unref?.();
728
+
729
+ const pingTimer = setInterval(() => {
730
+ for (const client of clients) client.ping();
731
+ }, 30000);
732
+ pingTimer.unref?.();
733
+
734
+ return {
735
+ port,
736
+ origin,
737
+ wsOrigin,
738
+ addresses: lanAddresses(),
739
+ linkBase: `${origin}/lan.html`,
740
+ qrSvg,
741
+ info() {
742
+ return { port, origin, wsOrigin, addresses: this.addresses, linkBase: this.linkBase };
743
+ },
744
+ close() {
745
+ clearInterval(idleTimer);
746
+ clearInterval(pingTimer);
747
+ for (const room of Array.from(rooms.values())) closeRoom(room);
748
+ for (const client of Array.from(clients)) client.terminate();
749
+ clients.clear();
750
+ rooms.clear();
751
+ server.close();
752
+ },
753
+ };
754
+ }
755
+
756
+ /** Execute a function only when run as a script (not imported by DSH). */
757
+ if (process.argv[1] && resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'))) {
758
+ const root = resolve(new URL('.', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'));
759
+ startLanServer({ root }).then((handle) => {
760
+ console.log(`[dsh-gomoku] LAN server: ${handle.origin}/lan.html`);
761
+ }).catch((error) => {
762
+ console.error('[dsh-gomoku] LAN server failed:', error);
763
+ process.exitCode = 1;
764
+ });
765
+ }