@@ -2,6 +2,9 @@ const WebSocket = require('ws');
22const service = require ( './data' ) ;
33const path = require ( 'path' ) ;
44
5+ const http = require ( 'http' ) ;
6+ const fs = require ( 'fs' ) ;
7+
58const originalLog = console . log ;
69console . log = function ( ) {
710 const date = new Date ( ) ;
@@ -12,10 +15,39 @@ console.log = function() {
1215
1316 originalLog . apply ( console , [ `[${ timestamp } ]` , ...arguments ] ) ;
1417} ;
18+ const HTTP_PORT = process . argv [ 2 ] || 8081 ; // 合并后的统一端口
19+ const HTTP_DIRECTORY = path . join ( __dirname , 'www' ) ; // 静态文件目录
20+
21+ // 创建 HTTP 服务器
22+ const server = http . createServer ( ( req , res ) => {
23+ let urlPath = decodeURIComponent ( req . url . split ( '?' ) [ 0 ] ) ; // 去掉查询参数
24+ if ( urlPath === '/' ) {
25+ urlPath = '/index.html' ; // 默认访问 index.html
26+ }
27+ let filePath = path . join ( HTTP_DIRECTORY , urlPath ) ;
28+ fs . stat ( filePath , ( err , stats ) => {
29+ if ( err || ! stats . isFile ( ) ) {
30+ // 如果文件不存在,返回 index.html
31+ filePath = path . join ( HTTP_DIRECTORY , 'index.html' ) ;
32+ }
33+
34+ // 设置缓存头
35+ const ext = path . extname ( filePath ) ;
36+ if ( ext === '.js' || ext === '.css' ) {
37+ res . setHeader ( 'Cache-Control' , 'public, max-age=2592000' ) ; // 30天缓存
38+ }
39+
40+ fs . createReadStream ( filePath ) . pipe ( res ) ;
41+ } ) ;
42+ } ) ;
43+
44+ server . listen ( HTTP_PORT , ( ) => {
45+ console . log ( `server start on port ${ HTTP_PORT } ` ) ;
46+ } ) ;
47+
48+
49+ const wsServer = new WebSocket . Server ( { server } ) ;
1550
16- // 接收启动参数作为端口号,默认8081
17- const PORT = process . argv [ 2 ] || 8081 ;
18- const server = new WebSocket . Server ( { port : PORT } ) ;
1951
2052const SEND_TYPE_REG = '1001' ; // 注册后发送用户id
2153const SEND_TYPE_ROOM_INFO = '1002' ; // 发送房间信息
@@ -44,15 +76,13 @@ try {
4476 } ) ;
4577 console . log ( `加载房间数据: ${ roomIds . join ( ',' ) } ` ) ;
4678} catch ( e ) {
47- console . error ( 'Failed to load room_pwd.json' ) ;
79+ // 没有room_pwd.json文件无需报错,不加载即可
80+ // console.error('Failed to load room_pwd.json');
4881}
4982
50- console . log ( `Signaling server running on ws://localhost:${ PORT } ` ) ;
51-
52- server . on ( 'connection' , ( socket , request ) => {
83+ wsServer . on ( 'connection' , ( socket , request ) => {
5384 const ip = request . headers [ 'x-forwarded-for' ] ?? request . headers [ 'x-real-ip' ] ?? socket . _socket . remoteAddress . split ( "::ffff:" ) . join ( "" ) ;
54-
55- const urlWithPath = request . url . split ( '/' )
85+ const urlWithPath = request . url . replace ( / ^ \/ / g, '' ) . split ( '/' )
5686 let roomId = null ;
5787 let pwd = null ;
5888 if ( urlWithPath . length > 1 && urlWithPath [ 1 ] . length > 0 && urlWithPath [ 1 ] . length <= 32 ) {
0 commit comments