sheep-realms / Echo-Live-WebSocket-Server

适用于 Echo-Live 的简易 WebSocket 服务器
GNU General Public License v3.0
4 stars 0 forks source link

【新功能请求】希望添加https #1

Open yandujun363 opened 2 hours ago

yandujun363 commented 2 hours ago

由于我echo-live部署的协议是https所以ws无法连接
于是就自己改了一下main.js的代码

if (config.https == true) {

    const http = require('https');//设置模块

    let options = {//设置密钥对
        key: fs.readFileSync(config.key_path),
        cert: fs.readFileSync(config.crt_path)
    };

    const server = http.createServer(options,(req, res) => {//添加options参数

        let filePath = '.' + req.url;
        if (filePath === './') {
            filePath = config.home_page;
        }

        const extname = String(path.extname(filePath)).toLowerCase();

        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',
            '.wav': 'audio/wav',
            '.mp4': 'video/mp4',
            '.woff': 'application/font-woff',
            '.ttf': 'application/font-ttf',
            '.eot': 'application/vnd.ms-fontobject',
            '.otf': 'application/font-otf',
            '.xml': 'text/xml',
            '.txt': 'text/plain',
        };

        const contentType = mimeTypes[extname] || 'application/octet-stream';

        // 读取文件并返回响应
        fs.readFile(filePath, (error, content) => {
            if (error) {
                if (error.code === 'ENOENT') {
                    res.writeHead(404, { 'Content-Type': 'text/html' });
                    res.end('<h1>404 Not Found</h1>', 'utf-8');
                } else {
                    res.writeHead(500);
                    res.end('Sorry, there was an error: ' + error.code + '..\n', 'utf-8');
                }
            } else {
                res.writeHead(200, { 'Content-Type': contentType });
                res.end(content, 'utf-8');
            }
        });
    });

    server.listen(config.port, () => {
        logOutput(`Server is running at https://${config.name}:${config.port}/`, 'success');
        logOutput(`WebSocket server at wss://${config.name}:${config.port}/`, 'success');
        if (localIPList.length > 0) {
            logOutput('Your LAN IP may be:');
            localIPList.forEach(e => {
                logOutput(e);
            });
        }
    });

    const wss = new WebSocket.Server({ server });
    const clients = new Set();

    wss.on('connection', (ws) => {
        logOutput('New client connect', 'success');
        clients.add(ws);

        ws.on('message', (message) => {
            let messageString;
            if (Buffer.isBuffer(message)) {
                messageString = message.toString();
            } else if (typeof message === 'string') {
                messageString = message;
            } else {
                try {
                    messageString = JSON.stringify(message);
                } catch (error) {
                    logOutput('Message type error', 'error');
                }
            }
            logOutput(`Received: ${messageString}`);

            clients.forEach(client => {
                if (client !== ws && client.readyState === WebSocket.OPEN) {
                    client.send(messageString);
                }
            });
        });

        ws.on('close', () => {
            logOutput('Client disconnected', 'warn');
            clients.delete(ws);
        });
    });
}

if (config.https == false) {

    const http = require('http');

    const server = http.createServer((req, res) => {
        let filePath = '.' + req.url;
        if (filePath === './') {
            filePath = config.home_page;
        }

        const extname = String(path.extname(filePath)).toLowerCase();

        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',
            '.wav': 'audio/wav',
            '.mp4': 'video/mp4',
            '.woff': 'application/font-woff',
            '.ttf': 'application/font-ttf',
            '.eot': 'application/vnd.ms-fontobject',
            '.otf': 'application/font-otf',
            '.xml': 'text/xml',
            '.txt': 'text/plain',
        };

        const contentType = mimeTypes[extname] || 'application/octet-stream';

        // 读取文件并返回响应
        fs.readFile(filePath, (error, content) => {
            if (error) {
                if (error.code === 'ENOENT') {
                    res.writeHead(404, { 'Content-Type': 'text/html' });
                    res.end('<h1>404 Not Found</h1>', 'utf-8');
                } else {
                    res.writeHead(500);
                    res.end('Sorry, there was an error: ' + error.code + '..\n', 'utf-8');
                }
            } else {
                res.writeHead(200, { 'Content-Type': contentType });
                res.end(content, 'utf-8');
            }
        });
    });

    server.listen(config.port, () => {
        logOutput(`Server is running at http://${config.name}:${config.port}/`, 'success');
        logOutput(`WebSocket server at ws://${config.name}:${config.port}/`, 'success');
        if (localIPList.length > 0) {
            logOutput('Your LAN IP may be:');
            localIPList.forEach(e => {
                logOutput(e);
            });
        }
    });

    const wss = new WebSocket.Server({ server });
    const clients = new Set();

    wss.on('connection', (ws) => {
        logOutput('New client connect', 'success');
        clients.add(ws);

        ws.on('message', (message) => {
            let messageString;
            if (Buffer.isBuffer(message)) {
                messageString = message.toString();
            } else if (typeof message === 'string') {
                messageString = message;
            } else {
                try {
                    messageString = JSON.stringify(message);
                } catch (error) {
                    logOutput('Message type error', 'error');
                }
            }
            logOutput(`Received: ${messageString}`);

            clients.forEach(client => {
                if (client !== ws && client.readyState === WebSocket.OPEN) {
                    client.send(messageString);
                }
            });
        });

        ws.on('close', () => {
            logOutput('Client disconnected', 'warn');
            clients.delete(ws);
        });
    });
}

json的修改

{
    "https": true,
    "name":"echo-live.yangdujun.ly",
    "home_page": "./editor.html",
    "port": 2100,
    "key_path": "./_.yangdujun.ly.pem",
    "crt_path": "./_.yangdujun.ly.crt"
}

虽然我觉得应该可以优化,但不知道怎么写

sheep-realms commented 2 hours ago

其实你可以直接提交 pr 的。我对 node.js 还不是很熟悉,再加上我最近比较忙,重心都放在了下个大版本的开发上,所以我需要一些时间来研究这个更改。