"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SocketService = exports.closeWebSocketServer = void 0;
// const net = require('net');
var net = require("net");
var uid_1 = require("uid");
var ssh_service_1 = require("./ssh.service");
var ws_1 = require("ws");
var moment = require("moment");
// const dgram = require('dgram')
var dgram = require("dgram");
var https = require("https");
var http2 = require("http2");
var utils_1 = require("./utils");
// const http = require('http')
var fs = require("fs");
var tls = require("tls");
var zlib = require("zlib");
// http2.constants.NGHTTP2_SETTINGS_TIMEOUT
function parseRequestHeader(text) {
    // const text = [
    //     'GET / HTTP/1.1',
    //     'user-agent: vscode-restclient',
    //     'accept-encoding: gzip',
    //     '',
    //     'hello'
    // ].join('\r\n')
    var lines = text.split(/\r\n/g);
    console.log('lines', lines);
    var headers = {};
    for (var i = 1; i < lines.length; i++) {
        var headerLine = lines[i];
        var _a = headerLine.split(':'), key = _a[0], value = _a[1];
        if (key && value) {
            headers[key.toLowerCase().trim()] = value.toLowerCase().trim();
        }
        // const m = headerLine.match(/:/)
        // if (m) {
        //     console.log('m', m)
        //     const key = headerLine.substring(0, m.index).trim().toLowerCase()
        //     const value = headerLine.substring(m.index).trim().toLowerCase()
        //     headers[key] = value
        // }
    }
    console.log('headers', headers);
    return {
        headers: headers,
    };
}
// parseRequestHeader()
var fixed_key = "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAKCAQEAziPn0R8ZI8ET2G8CxJZruEUaHZhRqhRankXpPs4SC/tettpl\nnRXYFkkoN6O8UxBvoLRZ8H2CxUehpmz+EAlL05kbAWIZBDr6FGLAtEVyizxQEGvc\nUcsyOmUDsYBkc4yyuR0vPmZYImNlJA0AhqE7hBF1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) {
    if (defaultValue === void 0) { defaultValue = null; }
    return __awaiter(this, void 0, void 0, function () {
        var content;
        return __generator(this, function (_a) {
            content = fs.readFileSync(path, 'utf-8');
            // console.log('content', content)
            if (content) {
                return [2 /*return*/, JSON.parse(content)];
            }
            return [2 /*return*/, defaultValue];
        });
    });
}
// TCP 客户端
var g_tcpClients = []; // 界面创建的所有客户端
var g_tcpConnId2ClientMap = {}; // connectionId 2 client
// TCP 服务端
var g_tcpServers = [];
var g_tcpConnId2ServerMap = {}; // connectionId 2 client
// WebSocket 服务端
var g_id2SocketMap = {};
var g_wsServerClients = [];
var g_wsServers = [];
// WebSocket 客户端（客户端暂时没有用服务器做代理
// UDP 服务端
var g_udpServers = [];
// HTTP 服务端
var g_httpServer;
var g_httpsServer;
var g_http2Server;
function closeByConnectionId(connectionId) {
    return __awaiter(this, void 0, void 0, function () {
        var fItem;
        return __generator(this, function (_a) {
            fItem = g_wsServerClients.find(function (item) { return item.connectionId = connectionId; });
            if (fItem) {
                console.log('wss', fItem);
                fItem.socket.close();
                // TODO 性能
                g_wsServerClients = g_wsServerClients.filter(function (item) { return item.connectionId != connectionId; });
            }
            return [2 /*return*/];
        });
    });
}
function closeWebSocketServer(connectionId) {
    closeByConnectionId(connectionId);
}
exports.closeWebSocketServer = closeWebSocketServer;
var SocketService = /** @class */ (function () {
    function SocketService() {
    }
    SocketService.prototype._closeServerById = function (connectionId) {
        return __awaiter(this, void 0, void 0, function () {
            var server, _i, _a, client;
            return __generator(this, function (_b) {
                server = g_tcpConnId2ServerMap[connectionId];
                if (!server) {
                    console.log('找不到 server', connectionId);
                    return [2 /*return*/, {}];
                }
                // 先关闭客户端
                for (_i = 0, _a = server.clients; _i < _a.length; _i++) {
                    client = _a[_i];
                    try {
                        client.socket.end();
                        // item.socket.destroy()
                    }
                    catch (err) {
                        console.log('tcpCloseServer/err', err);
                    }
                }
                server.clients = [];
                // 再关闭服务端
                console.log('g_tcpServer.listening', server._server.listening);
                // console.log('g_tcpServer.connections', g_tcpServer.connections)
                server._server.getConnections(function (err, count) {
                    console.log('getConnections', count, err);
                });
                if (server._server.listening) {
                    server._server.close(function (err) {
                        if (err) {
                            console.log('g_tcpServer.close/err', err);
                            return;
                        }
                        console.log('g_tcpServer.closed');
                    });
                }
                g_tcpServers = g_tcpServers.filter(function (item) { return item.id != connectionId; });
                delete g_tcpConnId2ServerMap[connectionId];
                console.log('g_tcpServer.closed');
                return [2 /*return*/];
            });
        });
    };
    SocketService.prototype.createTcpClient = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var host, port, _a, isTls, webSocketId, connectionId, _tcpConnect, _tlsTcpConnect;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        console.log('tcpConnect');
                        host = body.host, port = body.port, _a = body.isTls, isTls = _a === void 0 ? false : _a, webSocketId = body.webSocketId;
                        connectionId = (0, uid_1.uid)(32);
                        _tcpConnect = function () {
                            return new Promise(function (resolve, reject) {
                                var socket = new net.Socket();
                                var isConnected = false;
                                socket.connect(port, host, function () {
                                    console.log('tcp_client/socket.connect callback', port, host);
                                });
                                socket.setEncoding('utf-8');
                                socket.on('data', function (msg) {
                                    console.log('tcp_client/on/data', msg.toString());
                                    var client = g_tcpConnId2ClientMap[connectionId];
                                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    (0, ssh_service_1.sendTcpMsg)({
                                        webSocketId: webSocketId,
                                        // connectionId,
                                        message: {
                                            type: 'message',
                                            data: {
                                                id: (0, uid_1.uid)(8),
                                                time: time,
                                                content: msg.toString(client._hex ? 'hex' : 'utf-8'),
                                                contentType: client._hex ? 'hex' : 'text',
                                                type: 'message',
                                            }
                                        }
                                    });
                                });
                                socket.on('error', function (err) {
                                    console.log('tcp_client/on/error', err);
                                    if (!isConnected) {
                                        reject(err);
                                    }
                                });
                                socket.on('connect', function () {
                                    console.log('tcp_client/on/connect');
                                    isConnected = true;
                                    resolve(null);
                                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    (0, ssh_service_1.sendTcpMsg)({
                                        webSocketId: webSocketId,
                                        message: {
                                            type: 'connected',
                                            data: {
                                                id: (0, uid_1.uid)(8),
                                                time: time,
                                                type: 'info',
                                                host: host,
                                                port: port,
                                            }
                                        }
                                    });
                                });
                                socket.on('close', function () {
                                    console.log('tcp_client/on/close');
                                    if (!isConnected) {
                                        return;
                                    }
                                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    (0, ssh_service_1.sendTcpMsg)({
                                        webSocketId: webSocketId,
                                        message: {
                                            type: 'disconnected',
                                            data: {
                                                id: (0, uid_1.uid)(8),
                                                time: time,
                                                type: 'info',
                                                // host,
                                                // port,
                                            }
                                        }
                                    });
                                    // sendTcpMsg({
                                    //     webSocketId,
                                    //     message: {
                                    //         type: 'info',
                                    //         data: {
                                    //             id: uid(8),
                                    //             time,
                                    //             content: `系统信息：已断开连接`,
                                    //             type: 'info',
                                    //         }
                                    //     }
                                    // })
                                });
                                var client = {
                                    id: connectionId,
                                    config: {},
                                    _webSocketId: webSocketId,
                                    _hex: false,
                                    _socket: socket,
                                };
                                g_tcpClients.push(client);
                                g_tcpConnId2ClientMap[connectionId] = client;
                            });
                        };
                        _tlsTcpConnect = function () {
                            return new Promise(function (resolve, reject) {
                                var isConnected = false;
                                var options = {
                                    host: host,
                                    port: port,
                                    key: Buffer.from(fixed_key),
                                    cert: Buffer.from(fixed_crt),
                                    // ca: [ fs.readFileSync('./local.yunser.com.crt') ],
                                    rejectUnauthorized: true
                                };
                                var client = tls.connect(options, function () {
                                    isConnected = true;
                                    console.log('client connected', client.authorized ? 'authorized' : 'unauthorized');
                                    // process.stdin.setEncoding('utf8');
                                    // process.stdin.on('readable', function() {
                                    //         var chunk = process.stdin.read();
                                    //         if (chunk !== null) {
                                    //                 client.write(chunk);
                                    //         }
                                    // });
                                    // client.write("happy new year!");
                                    // console.log('client/write_ok', )
                                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    (0, ssh_service_1.sendTcpMsg)({
                                        webSocketId: webSocketId,
                                        message: {
                                            type: 'connected',
                                            data: {
                                                id: (0, uid_1.uid)(8),
                                                time: time,
                                                type: 'info',
                                                host: host,
                                                port: port,
                                            }
                                        }
                                    });
                                    resolve(null);
                                });
                                client.setEncoding('utf8');
                                client.on('data', function (data) {
                                    console.log(data);
                                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    (0, ssh_service_1.sendTcpMsg)({
                                        webSocketId: webSocketId,
                                        // connectionId,
                                        message: {
                                            type: 'message',
                                            data: {
                                                id: (0, uid_1.uid)(8),
                                                time: time,
                                                content: data.toString(client['_hex'] ? 'hex' : 'utf-8'),
                                                contentType: client['_hex'] ? 'hex' : 'text',
                                                type: 'message',
                                                isTls: true,
                                            }
                                        }
                                    });
                                });
                                client.on('error', function (err) {
                                    console.log('_tlsTcpConnect/error', err);
                                });
                                client.on('error', function (err) {
                                    console.log('_tlsTcpConnect/on/error', err);
                                    if (!isConnected) {
                                        reject(err);
                                    }
                                });
                                client.on('close', function (err) {
                                    console.log('_tlsTcpConnect/close', err);
                                    if (!isConnected) {
                                        return;
                                    }
                                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    (0, ssh_service_1.sendTcpMsg)({
                                        webSocketId: webSocketId,
                                        message: {
                                            type: 'disconnected',
                                            data: {
                                                id: (0, uid_1.uid)(8),
                                                time: time,
                                                type: 'info',
                                                // host,
                                                // port,
                                            }
                                        }
                                    });
                                });
                                var _client = {
                                    id: connectionId,
                                    config: {},
                                    _webSocketId: webSocketId,
                                    _hex: false,
                                    _socket: client,
                                };
                                g_tcpClients.push(_client);
                                g_tcpConnId2ClientMap[connectionId] = _client;
                            });
                        };
                        if (!isTls) return [3 /*break*/, 2];
                        return [4 /*yield*/, _tlsTcpConnect()];
                    case 1:
                        _b.sent();
                        return [3 /*break*/, 4];
                    case 2: return [4 /*yield*/, _tcpConnect()];
                    case 3:
                        _b.sent();
                        _b.label = 4;
                    case 4: return [2 /*return*/, {
                            connectionId: connectionId,
                        }];
                }
            });
        });
    };
    SocketService.prototype.tcpConfig = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, _a, hex, client;
            return __generator(this, function (_b) {
                connectionId = body.connectionId, _a = body.hex, hex = _a === void 0 ? false : _a;
                client = g_tcpConnId2ClientMap[connectionId];
                client._hex = hex;
                return [2 /*return*/, {}];
            });
        });
    };
    SocketService.prototype.tcpSend = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, _a, contentType, content, client, _sendContent, webSocketId, _send;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        connectionId = body.connectionId, _a = body.contentType, contentType = _a === void 0 ? 'text' : _a, content = body.content;
                        client = g_tcpConnId2ClientMap[connectionId];
                        if (contentType == 'hex') {
                            _sendContent = Buffer.from(content, 'hex');
                        }
                        else {
                            _sendContent = content;
                        }
                        webSocketId = client._webSocketId;
                        _send = function () {
                            return new Promise(function (resolve, reject) {
                                client._socket.write(_sendContent, function (err) {
                                    if (err) {
                                        console.log('send/error', err);
                                        reject(err);
                                    }
                                    console.log('send/success');
                                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    (0, ssh_service_1.sendTcpMsg)({
                                        webSocketId: webSocketId,
                                        message: {
                                            type: 'sent',
                                            data: {
                                                id: (0, uid_1.uid)(8),
                                                time: time,
                                                content: content,
                                                contentType: contentType,
                                                type: 'sent',
                                            }
                                        }
                                    });
                                    resolve(null);
                                });
                            });
                        };
                        return [4 /*yield*/, _send()];
                    case 1:
                        _b.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    SocketService.prototype.tcpClose = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, client;
            return __generator(this, function (_a) {
                connectionId = body.connectionId;
                client = g_tcpConnId2ClientMap[connectionId];
                client._socket && client._socket.destroy();
                client._socket = null;
                g_tcpClients = g_tcpClients.filter(function (item) { return item.id != connectionId; });
                delete g_tcpConnId2ClientMap[connectionId];
                return [2 /*return*/, {}];
            });
        });
    };
    SocketService.prototype.udpSend = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var content, port, host, webSocketId, g_udp_client, _send;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        content = body.content, port = body.port, host = body.host, webSocketId = body.webSocketId;
                        g_udp_client = dgram.createSocket('udp4');
                        g_udp_client.on('close', function () {
                            console.log('g_udp_client/close');
                        });
                        g_udp_client.on('connect', function () {
                            console.log('g_udp_client/connect');
                        });
                        g_udp_client.on('listening', function () {
                            var address = g_udp_client.address();
                            console.log('g_udp_client/listening', "".concat(address.address, ":").concat(address.port, " F: ").concat(address.family));
                        });
                        g_udp_client.on('error', function (err) {
                            console.log('g_udp_client/error', err);
                        });
                        g_udp_client.on('message', function (msg, rinfo) {
                            // if (msg == 'exit') g_udp_client.close();
                            // var strmsg = msg.toString();
                            console.log("g_udp_client/message/\u63A5\u6536\u5230\u6765\u81EA\uFF1A".concat(rinfo.address, ":").concat(rinfo.port, " \u7684\u6D88\u606F\uFF1A ").concat(msg));
                        });
                        _send = function () {
                            return new Promise(function (resolve, reject) {
                                g_udp_client.send(content, port, host, function (err) {
                                    if (err) {
                                        // client.close();
                                        console.log('g_udp_client/error', err);
                                        reject(err);
                                        return;
                                    }
                                    console.log('g_udp_client/send/ok');
                                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    (0, ssh_service_1.sendTcpMsg)({
                                        webSocketId: webSocketId,
                                        message: {
                                            type: 'sent',
                                            data: {
                                                id: (0, uid_1.uid)(8),
                                                time: time,
                                                content: content,
                                                // contentType,
                                                type: 'sent',
                                            }
                                        }
                                    });
                                    g_udp_client.close();
                                    resolve(null);
                                });
                            });
                        };
                        return [4 /*yield*/, _send()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    SocketService.prototype.udpCreateServer = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var port, host, webSocketId, connectionId, _createServer;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        port = body.port, host = body.host, webSocketId = body.webSocketId;
                        connectionId = (0, uid_1.uid)(32);
                        _createServer = function () {
                            return new Promise(function (resolve, reject) {
                                var hasConnected = false;
                                var server = dgram.createSocket('udp4');
                                g_udpServers.push({
                                    id: connectionId,
                                    _socket: server,
                                    _webSocketId: webSocketId,
                                });
                                server.on('error', function (err) {
                                    console.log("udp_server/err\uFF1A\n".concat(err.stack));
                                    if (!hasConnected) {
                                        server.close();
                                        reject(err);
                                    }
                                });
                                server.on('message', function (msg, rinfo) {
                                    var strmsg = msg.toString();
                                    console.log("udp_server/message ".concat(rinfo.address, ":").concat(rinfo.port, " \u7684\u6D88\u606F"));
                                    // console.log('strmsg', strmsg)
                                    // server.send(strmsg, rinfo.port, rinfo.address)
                                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    (0, ssh_service_1.sendTcpMsg)({
                                        webSocketId: webSocketId,
                                        message: {
                                            type: 'message',
                                            data: {
                                                type: 'message',
                                                time: time,
                                                id: (0, uid_1.uid)(8),
                                                host: rinfo.address,
                                                port: rinfo.port,
                                                content: strmsg,
                                            }
                                        }
                                    });
                                });
                                server.on('listening', function () {
                                    hasConnected = true;
                                    var address = server.address();
                                    console.log("udp_server/listening ".concat(address.address, ":").concat(address.port, " F:").concat(address.family));
                                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    (0, ssh_service_1.sendTcpMsg)({
                                        webSocketId: webSocketId,
                                        message: {
                                            type: 'listening',
                                            data: {
                                                type: 'info',
                                                time: time,
                                                id: (0, uid_1.uid)(8),
                                                host: host,
                                                port: port,
                                            }
                                        }
                                    });
                                    resolve(null);
                                });
                                server.on('connect', function () {
                                    console.log('udp_server/connect');
                                });
                                server.on('close', function () {
                                    console.log('udp_server/close');
                                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    (0, ssh_service_1.sendTcpMsg)({
                                        webSocketId: webSocketId,
                                        message: {
                                            type: 'close',
                                            data: {
                                                type: 'close',
                                                time: time,
                                                id: (0, uid_1.uid)(8),
                                                // host,
                                                // port,
                                            }
                                        }
                                    });
                                });
                                server.bind(port, host);
                            });
                        };
                        return [4 /*yield*/, _createServer()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, {
                                connectionId: connectionId,
                            }];
                }
            });
        });
    };
    SocketService.prototype.tcpCreateServer = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var port, host, webSocketId, _a, isTls, _b, hex, connectionId, _createServer;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        port = body.port, host = body.host, webSocketId = body.webSocketId, _a = body.isTls, isTls = _a === void 0 ? false : _a, _b = body.hex, hex = _b === void 0 ? false : _b;
                        connectionId = (0, uid_1.uid)(32);
                        _createServer = function () {
                            return new Promise(function (resolve, reject) {
                                var options = {};
                                if (isTls) {
                                    options = __assign(__assign({}, options), { key: Buffer.from(fixed_key), cert: Buffer.from(fixed_crt), 
                                        // // This is necessary only if the client uses the self-signed certificate.
                                        //     ca: [ fs.readFileSync('./local.yunser.com.crt') ],
                                        // // This is necessary only if using the client certificate authentication.
                                        // requestCert: true,
                                        // rejectUnauthorized: true
                                        requestCert: false, rejectUnauthorized: false });
                                }
                                var server = isTls ? tls.createServer(options) : net.createServer();
                                var isSuccess = false;
                                var _server = {
                                    id: connectionId,
                                    _webSocketId: webSocketId,
                                    _hex: hex,
                                    clients: [],
                                    _server: server
                                };
                                g_tcpServers.push(_server);
                                g_tcpConnId2ServerMap[connectionId] = _server;
                                var connectionHandler = function (client, isTls) {
                                    if (isTls === void 0) { isTls = false; }
                                    var clientId = (0, uid_1.uid)(8);
                                    // client.setEncoding = 'UTF-8';
                                    console.log("tcp_server/connection/\u5BA2\u6237\u7AEF".concat(clientId, "\u94FE\u63A5\u4E86"));
                                    // client.name = ++clientName; // 给每一个client起个名
                                    // clients[client.name] = client; // 将client保存在clients
                                    client.on('data', function (msg) {
                                        console.log("tcp_server/\u5BA2\u6237\u7AEF".concat(clientId, "\u53D1\u6765\u4E00\u4E2A\u4FE1\u606F\uFF1A").concat(msg));
                                        // console.log(`=${msg}=`, typeof msg)
                                        var server = g_tcpConnId2ServerMap[connectionId];
                                        var _msg = msg.toString(server._hex ? 'hex' : 'utf-8').replace(/^\s+/, '').replace(/\s+$/, '');
                                        // msg.toString()
                                        // console.log(`2=${_msg}=`, typeof _msg)
                                        var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                        (0, ssh_service_1.sendTcpMsg)({
                                            webSocketId: webSocketId,
                                            message: {
                                                type: 'client_message',
                                                data: {
                                                    id: (0, uid_1.uid)(8),
                                                    time: time,
                                                    // content: `系统信息：客户端${clientId}发来一个信息：${msg}`,
                                                    content: msg.toString(server._hex ? 'hex' : 'utf-8'),
                                                    contentType: server._hex ? 'hex' : 'text',
                                                    clientId: clientId,
                                                    type: 'message',
                                                }
                                            }
                                        });
                                        if (_msg == 'ping') {
                                            console.log("tcp_server/pong to ".concat(clientId));
                                            var content = 'pong';
                                            client.write(content, function (err) {
                                                if (err) {
                                                    console.log('send_err', err);
                                                    // code: 'EPIPE'
                                                    // ERR_STREAM_DESTROYED
                                                }
                                                else {
                                                    console.log('send_ok');
                                                    // socket.destroy()
                                                }
                                            });
                                            var time_1 = moment().format('YYYY-MM-DD HH:mm:ss');
                                            (0, ssh_service_1.sendTcpMsg)({
                                                webSocketId: server._webSocketId,
                                                message: {
                                                    type: 'client_send',
                                                    data: {
                                                        id: (0, uid_1.uid)(8),
                                                        time: time_1,
                                                        // content: `系统信息：客户端${clientId}发来一个信息：${msg}`,
                                                        content: content,
                                                        // contentType,
                                                        clientId: clientId,
                                                        type: 'message',
                                                    }
                                                }
                                            });
                                        }
                                        // if (_msg == 'exit') {
                                        //     client.destroy()
                                        // }
                                    });
                                    client.on('error', function (e) {
                                        console.log('tcp_server/client error' + e);
                                        client.end();
                                    });
                                    client.on('close', function () {
                                        // delete clients[client.name];
                                        console.log("tcp_server/\u5BA2\u6237\u7AEF".concat(clientId, "\u4E0B\u7EBF\u4E86"));
                                        var server = g_tcpConnId2ServerMap[connectionId];
                                        server.clients = server.clients.filter(function (item) { return item.id != clientId; });
                                        var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                        (0, ssh_service_1.sendTcpMsg)({
                                            webSocketId: webSocketId,
                                            message: {
                                                id: (0, uid_1.uid)(8),
                                                time: time,
                                                type: 'client_disconnected',
                                                data: {
                                                    type: 'info',
                                                    clientId: clientId,
                                                }
                                            }
                                        });
                                    });
                                    //设置最大连接数量
                                    // server.maxConnections = 3;
                                    // server.getConnections(function (err, count) {
                                    //     console.log("tcp_server/当前连接的客户端个数为：" + count);
                                    // })
                                    // client.write('hi')
                                    var address = client.address();
                                    // console.log('address', address)
                                    // console.log('client.remoteAddress', client.remoteAddress)
                                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    var server = g_tcpConnId2ServerMap[connectionId];
                                    server.clients.unshift({
                                        id: clientId,
                                        socket: client,
                                        connectTime: time,
                                    });
                                    (0, ssh_service_1.sendTcpMsg)({
                                        webSocketId: webSocketId,
                                        message: {
                                            id: (0, uid_1.uid)(8),
                                            time: time,
                                            type: 'client_connected',
                                            data: {
                                                type: 'info',
                                                clientId: clientId,
                                                address: address,
                                            },
                                        }
                                    });
                                };
                                if (isTls) {
                                    server.on('secureConnection', function (client) { return connectionHandler(client, true); });
                                }
                                else {
                                    server.on('connection', function (client) { return connectionHandler(client, false); });
                                }
                                //设置监听时的回调函数
                                server.on('listening', function () {
                                    isSuccess = true;
                                    resolve(null);
                                    console.log('tcp_server/listening');
                                    var address = server.address();
                                    console.log('address', address);
                                    //获取地址详细信息
                                    // console.log("服务器监听的端口是：" + address.port);
                                    // console.log("服务器监听的地址是：" + address.address);
                                    // console.log("服务器监听的地址类型是：" + address.family);
                                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    (0, ssh_service_1.sendTcpMsg)({
                                        webSocketId: webSocketId,
                                        message: {
                                            type: 'listening',
                                            data: {
                                                type: 'info',
                                                time: time,
                                                id: (0, uid_1.uid)(8),
                                                host: host,
                                                port: port,
                                            }
                                        }
                                    });
                                });
                                server.on('close', function () {
                                    console.log('tcp_server/close');
                                    if (isSuccess) {
                                        var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                        (0, ssh_service_1.sendTcpMsg)({
                                            webSocketId: webSocketId,
                                            message: {
                                                type: 'close',
                                                data: {
                                                    type: 'info',
                                                    time: time,
                                                    id: (0, uid_1.uid)(8),
                                                }
                                            }
                                        });
                                    }
                                });
                                server.on('error', function (err) {
                                    console.log('tcp_server/error', err);
                                    // err.to
                                    if (!isSuccess) {
                                        server.close();
                                        reject(err);
                                    }
                                });
                                server.listen(port, host, function () {
                                    console.log("tcp_server/\u670D\u52A1\u8FD0\u884C\u5728\uFF1Ahttp://".concat(host, ":").concat(port));
                                });
                            });
                        };
                        return [4 /*yield*/, _createServer()];
                    case 1:
                        _c.sent();
                        return [2 /*return*/, {
                                connectionId: connectionId,
                            }];
                }
            });
        });
    };
    SocketService.prototype.tcpCloseServer = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        connectionId = body.connectionId;
                        return [4 /*yield*/, this._closeServerById(connectionId)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    SocketService.prototype.closeAllTcpServer = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var _i, g_tcpServers_1, server;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _i = 0, g_tcpServers_1 = g_tcpServers;
                        _a.label = 1;
                    case 1:
                        if (!(_i < g_tcpServers_1.length)) return [3 /*break*/, 4];
                        server = g_tcpServers_1[_i];
                        return [4 /*yield*/, this._closeServerById(server.id)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4:
                        g_wsServers = [];
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    SocketService.prototype.closeUdpServer = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId;
            return __generator(this, function (_a) {
                connectionId = body.connectionId;
                g_udpServers = g_udpServers.filter(function (item) {
                    if (item.id == connectionId) {
                        item._socket.close();
                    }
                    return item.id != connectionId;
                });
                return [2 /*return*/, {}];
            });
        });
    };
    SocketService.prototype.udpServerSend = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, content, port, host, server, _send;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        connectionId = body.connectionId, content = body.content, port = body.port, host = body.host;
                        server = g_udpServers.find(function (item) { return item.id == connectionId; });
                        console.log('server', server, g_udpServers);
                        _send = function () {
                            return new Promise(function (resolve, reject) {
                                server._socket.send(content, port, host, function (err) {
                                    if (err) {
                                        // client.close();
                                        console.log('udpServerSend/error', err);
                                        reject(err);
                                        return;
                                    }
                                    console.log('udpServerSend/send/ok');
                                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                                    (0, ssh_service_1.sendTcpMsg)({
                                        webSocketId: server._webSocketId,
                                        message: {
                                            type: 'sent',
                                            data: {
                                                id: (0, uid_1.uid)(8),
                                                time: time,
                                                content: content,
                                                // contentType,
                                                type: 'sent',
                                                port: port,
                                                host: host,
                                            }
                                        }
                                    });
                                    resolve(null);
                                });
                            });
                        };
                        return [4 /*yield*/, _send()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    SocketService.prototype.closeAllUdpServer = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var _i, g_udpServers_1, server;
            return __generator(this, function (_a) {
                for (_i = 0, g_udpServers_1 = g_udpServers; _i < g_udpServers_1.length; _i++) {
                    server = g_udpServers_1[_i];
                    server._socket.close();
                }
                g_udpServers = [];
                return [2 /*return*/, {}];
            });
        });
    };
    SocketService.prototype.closeAllTcpClient = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var _i, g_tcpClients_1, client;
            return __generator(this, function (_a) {
                for (_i = 0, g_tcpClients_1 = g_tcpClients; _i < g_tcpClients_1.length; _i++) {
                    client = g_tcpClients_1[_i];
                    try {
                        client._socket && client._socket.destroy();
                    }
                    catch (err) {
                        console.log('closeAllClient/error', err);
                    }
                }
                g_tcpClients = [];
                return [2 /*return*/];
            });
        });
    };
    SocketService.prototype.serverSend = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, clientId, _a, contentType, content, server, _sendContent, _loop_1, _i, _b, client;
            return __generator(this, function (_c) {
                connectionId = body.connectionId, clientId = body.clientId, _a = body.contentType, contentType = _a === void 0 ? 'text' : _a, content = body.content;
                server = g_tcpConnId2ServerMap[connectionId];
                if (contentType == 'hex') {
                    _sendContent = Buffer.from(content, 'hex');
                }
                else {
                    _sendContent = content;
                }
                _loop_1 = function (client) {
                    if (!clientId || client.id == clientId) {
                        client.socket.write(_sendContent, function (err) {
                            if (err) {
                                console.log('serverSend/err', err);
                                return;
                            }
                            console.log('serverSend/ok');
                            var time = moment().format('YYYY-MM-DD HH:mm:ss');
                            (0, ssh_service_1.sendTcpMsg)({
                                webSocketId: server._webSocketId,
                                message: {
                                    type: 'client_send',
                                    data: {
                                        id: (0, uid_1.uid)(8),
                                        time: time,
                                        // content: `系统信息：客户端${clientId}发来一个信息：${msg}`,
                                        content: content,
                                        contentType: contentType,
                                        clientId: client.id,
                                        type: 'message',
                                    }
                                }
                            });
                        });
                    }
                };
                for (_i = 0, _b = server.clients; _i < _b.length; _i++) {
                    client = _b[_i];
                    _loop_1(client);
                }
                return [2 /*return*/];
            });
        });
    };
    SocketService.prototype.serverConfig = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, _a, hex, server;
            return __generator(this, function (_b) {
                connectionId = body.connectionId, _a = body.hex, hex = _a === void 0 ? false : _a;
                server = g_tcpConnId2ServerMap[connectionId];
                server._hex = hex;
                return [2 /*return*/, {}];
            });
        });
    };
    SocketService.prototype.tcpClients = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, server;
            return __generator(this, function (_a) {
                connectionId = body.connectionId;
                server = g_tcpConnId2ServerMap[connectionId];
                // TODO 前端可能没处理好，hack
                if (!server) {
                    return [2 /*return*/, {
                            list: [],
                        }];
                }
                return [2 /*return*/, {
                        list: server.clients,
                    }];
            });
        });
    };
    SocketService.prototype.tcpCloseClient = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, id, server;
            return __generator(this, function (_a) {
                connectionId = body.connectionId, id = body.id;
                server = g_tcpConnId2ServerMap[connectionId];
                server.clients = server.clients.filter(function (item) {
                    if (!id || item.id == id) {
                        try {
                            item.socket.end();
                            // item.socket.destroy()
                        }
                        catch (err) {
                            console.log('tcpCloseClient/err', err);
                        }
                    }
                    return item.id != id;
                });
                return [2 /*return*/];
            });
        });
    };
    SocketService.prototype.createWebSocketServer = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, port, connectionId, wss;
            return __generator(this, function (_b) {
                _a = body.port, port = _a === void 0 ? 80 : _a;
                connectionId = (0, uid_1.uid)(32);
                wss = new ws_1.WebSocket.Server({
                    port: port,
                });
                wss.on('connection', function (ws) {
                    var _this = this;
                    var clientId = (0, uid_1.uid)(16);
                    console.log('websocketServer/connection', clientId);
                    // createSocket(ws);
                    g_id2SocketMap[clientId] = ws;
                    g_wsServers.push({
                        id: clientId,
                        connectTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                        // socket: ws,
                    });
                    ws.on('message', function (data) { return __awaiter(_this, void 0, void 0, function () {
                        var msgContent;
                        return __generator(this, function (_a) {
                            msgContent = data.toString();
                            console.log('websocketServer/message', msgContent);
                            (0, ssh_service_1.sendWebSocketMsg)({
                                connectionId: connectionId,
                                message: {
                                    type: 'reveiveMessage',
                                    data: {
                                        id: (0, uid_1.uid)(8),
                                        time: moment().format('YYYY-MM-DD HH:mm:ss'),
                                        clientId: clientId,
                                        message: msgContent,
                                    }
                                }
                            });
                            return [2 /*return*/];
                        });
                    }); });
                    ws.on("close", function () {
                        console.log('websocketServer/close', clientId);
                        g_wsServers = g_wsServers.filter(function (item) { return item.id != clientId; });
                        delete g_id2SocketMap[clientId];
                        (0, ssh_service_1.sendWebSocketMsg)({
                            connectionId: connectionId,
                            message: {
                                type: 'clientClose',
                                data: {
                                    id: (0, uid_1.uid)(8),
                                    time: moment().format('YYYY-MM-DD HH:mm:ss'),
                                    clientId: clientId,
                                },
                            }
                        });
                    });
                    console.log('sendWebSocketMsg/connectionId', connectionId);
                    (0, ssh_service_1.sendWebSocketMsg)({
                        connectionId: connectionId,
                        message: {
                            type: 'clientConnect',
                            data: {
                                id: (0, uid_1.uid)(8),
                                time: moment().format('YYYY-MM-DD HH:mm:ss'),
                                clientId: clientId,
                            },
                        }
                    });
                });
                wss.on('listening', function () {
                    console.log('wss/listening');
                });
                wss.on('close', function () {
                    console.log('wss/close');
                });
                wss.on('error', function (err) {
                    console.log('wss/error');
                });
                g_wsServerClients.push({
                    connectionId: connectionId,
                    socket: wss,
                });
                return [2 /*return*/, {
                        connectionId: connectionId,
                    }];
            });
        });
    };
    SocketService.prototype.closeWebSocketServer = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        connectionId = body.connectionId;
                        return [4 /*yield*/, closeByConnectionId(connectionId)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    SocketService.prototype.clients = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, {
                        list: g_wsServers,
                    }];
            });
        });
    };
    SocketService.prototype.sendToClient = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var clinetId, content, _i, g_wsServers_1, client, ws, _a, g_wsServers_2, client, ws;
            return __generator(this, function (_b) {
                clinetId = body.clinetId, content = body.content;
                if (clinetId) {
                    for (_i = 0, g_wsServers_1 = g_wsServers; _i < g_wsServers_1.length; _i++) {
                        client = g_wsServers_1[_i];
                        if (client.id == clinetId) {
                            ws = g_id2SocketMap[client.id];
                            if (ws) {
                                ws.send(content);
                            }
                        }
                    }
                }
                else {
                    for (_a = 0, g_wsServers_2 = g_wsServers; _a < g_wsServers_2.length; _a++) {
                        client = g_wsServers_2[_a];
                        ws = g_id2SocketMap[client.id];
                        if (ws) {
                            ws.send(content);
                        }
                    }
                }
                return [2 /*return*/, {}];
            });
        });
    };
    SocketService.prototype.closeClient = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, ws, _i, g_wsServers_3, client, ws;
            return __generator(this, function (_a) {
                id = body.id;
                if (id) {
                    ws = g_id2SocketMap[id];
                    if (ws) {
                        ws.close();
                    }
                    g_wsServers = g_wsServers.filter(function (item) { return item.id != id; });
                }
                else {
                    for (_i = 0, g_wsServers_3 = g_wsServers; _i < g_wsServers_3.length; _i++) {
                        client = g_wsServers_3[_i];
                        ws = g_id2SocketMap[client.id];
                        if (ws) {
                            ws.close();
                        }
                    }
                    g_wsServers = [];
                }
                return [2 /*return*/, {}];
            });
        });
    };
    SocketService.prototype.httpCreateServer = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, host, _b, port, webSocketId, server;
            return __generator(this, function (_c) {
                _a = body.host, host = _a === void 0 ? '0.0.0.0' : _a, _b = body.port, port = _b === void 0 ? 80 : _b, webSocketId = body.webSocketId;
                if (g_httpServer) {
                    g_httpServer.close();
                }
                server = net.createServer(function (socket) {
                    var _isEnd = false;
                    socket.on('data', function (data) {
                        var reqData = data.toString();
                        console.log('/data', reqData);
                        if (reqData.includes('/whoami')) {
                            var content = reqData;
                            socket.write("HTTP/1.1 200 OK\r\ncontent-length: ".concat(content.length, "\r\n\r\n"));
                            socket.write(content);
                            socket.end();
                        }
                        else if (reqData.includes('/sse')) {
                            // const content = reqData
                            var headers = [
                                'HTTP/1.1 200 OK',
                                'Content-Type: text/event-stream',
                                'Cache-Control: no-cache',
                                'Connection: keep-alive',
                                'Access-Control-Allow-Origin: *'
                            ].join('\r\n');
                            var content = [
                                'retry: 5',
                                '',
                                ':ping',
                                '',
                                'event: ping',
                                'data: ppp',
                                '',
                                'id: 001',
                                '',
                                'data: hello world',
                                '',
                                'id: 002',
                                '',
                                'data: hello world2',
                                '',
                                '',
                            ].join('\n');
                            console.log('content', content);
                            socket.write("HTTP/1.1 200 OK\r\n".concat(headers, "\r\n\r\n"));
                            socket.write(content);
                            socket.end();
                        }
                        else {
                            var resContent = 'hello http';
                            var reqHeaders = parseRequestHeader(reqData).headers;
                            var resHeaders_1 = {
                            // 'content-length': resContent.length,
                            };
                            var buffer = void 0;
                            console.log('reqHeaders', reqHeaders);
                            var acceptEncodings = [];
                            if (reqHeaders['accept-encoding']) {
                                acceptEncodings = reqHeaders['accept-encoding'].split(',').map(function (item) { return item.trim(); });
                            }
                            console.log('acceptEncodings', acceptEncodings);
                            if (acceptEncodings.includes('gzip')) {
                                resHeaders_1['Content-Encoding'] = 'gzip';
                                var originBuffer = Buffer.from(resContent);
                                buffer = zlib.gzipSync(originBuffer);
                            }
                            else if (acceptEncodings.includes('deflate')) {
                                resHeaders_1['Content-Encoding'] = 'deflate';
                                var originBuffer = Buffer.from(resContent);
                                buffer = zlib.deflateSync(originBuffer);
                            }
                            else if (acceptEncodings.includes('br')) {
                                resHeaders_1['Content-Encoding'] = 'br';
                                var originBuffer = Buffer.from(resContent);
                                buffer = zlib.brotliCompressSync(originBuffer);
                            }
                            else {
                                buffer = Buffer.from(resContent);
                            }
                            resHeaders_1['Content-Length'] = buffer.length;
                            var headersCode = Object.keys(resHeaders_1).map(function (key) { return "".concat(key, ": ").concat(resHeaders_1[key]); }).join('\r\n');
                            socket.write("HTTP/1.1 200 OK\r\n".concat(headersCode, "\r\n\r\n"));
                            socket.write(buffer);
                            socket.end();
                        }
                        // if (reqData.startsWith('GET')) {
                        //     // 如果是 GET 请求，则返回响应
                        // }
                        // else {
                        //     const content = 'Only support GET'
                        //     socket.write(`HTTP/1.1 400 Bad Request\r\ncontent-length: ${content.length}\r\n\r\n`)
                        //     socket.write(content)
                        //     socket.end()
                        // }
                        var time = moment().format('YYYY-MM-DD HH:mm:ss');
                        (0, ssh_service_1.sendTcpMsg)({
                            webSocketId: webSocketId,
                            message: {
                                type: 'request',
                                data: {
                                    id: (0, uid_1.uid)(8),
                                    time: time,
                                    content: "".concat(socket.remoteAddress, ":").concat(socket.remotePort, " \u8BF7\u6C42"),
                                    // contentType,
                                    type: 'request',
                                    port: socket.remotePort,
                                    host: socket.remoteAddress,
                                }
                            }
                        });
                    });
                    socket.on('close', function () {
                    });
                });
                server.on('connection', function (_socket) {
                    console.log('http_server/connection');
                    var addr = _socket.address();
                    console.log('addr', addr);
                })
                    .on('close', function () {
                    console.log('http_server/close');
                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                    (0, ssh_service_1.sendTcpMsg)({
                        webSocketId: webSocketId,
                        message: {
                            type: 'close',
                            data: {
                                id: (0, uid_1.uid)(8),
                                time: time,
                                // content,
                                // contentType,
                                type: 'close',
                                // port,
                                // host,
                            }
                        }
                    });
                })
                    .on('listening', function () {
                    console.log('http_server/listening');
                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                    (0, ssh_service_1.sendTcpMsg)({
                        webSocketId: webSocketId,
                        message: {
                            type: 'listening',
                            data: {
                                id: (0, uid_1.uid)(8),
                                time: time,
                                // content,
                                // contentType,
                                type: 'listening',
                                port: port,
                                host: host,
                            }
                        }
                    });
                })
                    .on('error', function (err) {
                    console.log('http_server/error', err);
                })
                    .listen(port, host, function () {
                });
                // const server = http.createServer((req, res) => {
                //     console.log('======== http_server/start', )
                //     // console.log('ip', req.ip)
                //     // console.log('req', req)
                //     console.log('localAddress', req.socket.localAddress)
                //     console.log('remoteAddress', req.socket.localPort)
                //     console.log('socket', req.socket.address())
                //     // console.log('socket', req.socket.address().family)
                //     console.log('headers', req.headers)
                //     // headers { host: '[::1]:6698', 'user-agent': 'curl/7.64.1', accept: '*/*' }
                //     // headers { host: '127.0.0.1:6698', 'user-agent': 'curl/7.64.1', accept: '*/*' }
                //     // headers { host: 'localhost:6698', 'user-agent': 'curl/7.64.1', accept: '*/*' }
                //     let removeAddr = req.headers['x-real-ip'] || req.socket.remoteAddress
                //     // if (removeAddr)
                //     // const text = `your IP: ${removeAddr}`
                //     const text = `hello http`
                //     // res.setHeader('content-lenth', text.length)
                //     // res.setHeader('x-power-by', 'DMS')
                //     res.writeHead(200, {
                //         'content-type': 'text/plain',
                //         'content-lenth': text.length,
                //         'x-power-by': 'DMS'
                //     })
                //     res.end(text)
                //     console.log('======== http_server/end', )
                //     // res.end('hello nodejs\n' + process.pid)
                //     const time = moment().format('YYYY-MM-DD HH:mm:ss')
                //     sendTcpMsg({
                //         webSocketId,
                //         message: {
                //             type: 'request',
                //             data: {
                //                 id: uid(8),
                //                 time,
                //                 content: `${req.socket.remoteAddress}:${req.socket.remotePort} 请求`,
                //                 // contentType,
                //                 type: 'request',
                //                 port: req.socket.remotePort,
                //                 host: req.socket.remoteAddress,
                //             }
                //         }
                //     })
                // })
                // .listen('[::]:80')
                // .listen('6788')
                // .listen('[::]:6699')
                // console.log('ok', )
                // console.log('process.pid', process.pid)
                g_httpServer = server;
                return [2 /*return*/, {}];
            });
        });
    };
    SocketService.prototype.httpsCreateServer = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, host, _b, port, webSocketId, options, _server;
            return __generator(this, function (_c) {
                _a = body.host, host = _a === void 0 ? '0.0.0.0' : _a, _b = body.port, port = _b === void 0 ? 80 : _b, webSocketId = body.webSocketId;
                options = {
                    //   key: fs.readFileSync('./server.key'),
                    //   cert: fs.readFileSync('./server.crt')
                    key: Buffer.from(fixed_key),
                    cert: Buffer.from(fixed_crt),
                };
                _server = https.createServer(options, function (req, res) {
                    console.log('======== client request');
                    var resContent = 'hello https';
                    res.writeHead(200, {
                        'content-length': resContent.length,
                    });
                    res.end(resContent);
                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                    (0, ssh_service_1.sendTcpMsg)({
                        webSocketId: webSocketId,
                        message: {
                            type: 'request',
                            data: {
                                id: (0, uid_1.uid)(8),
                                time: time,
                                content: "".concat(req.socket.remoteAddress, ":").concat(req.socket.remotePort, " \u8BF7\u6C42"),
                                // contentType,
                                type: 'request',
                                port: req.socket.remotePort,
                                host: req.socket.remoteAddress,
                            }
                        }
                    });
                })
                    .on('connect', function () {
                    console.log('https_server/connect');
                })
                    .on('connection', function () {
                    console.log('https_server/connection');
                })
                    .on('listening', function () {
                    console.log('http_server/listening');
                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                    (0, ssh_service_1.sendTcpMsg)({
                        webSocketId: webSocketId,
                        message: {
                            type: 'listening',
                            data: {
                                id: (0, uid_1.uid)(8),
                                time: time,
                                // content,
                                // contentType,
                                type: 'listening',
                                port: port,
                                host: host,
                            }
                        }
                    });
                })
                    .on('close', function () {
                    console.log('http_server/close');
                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                    (0, ssh_service_1.sendTcpMsg)({
                        webSocketId: webSocketId,
                        message: {
                            type: 'close',
                            data: {
                                id: (0, uid_1.uid)(8),
                                time: time,
                                // content,
                                // contentType,
                                type: 'close',
                                // port,
                                // host,
                            }
                        }
                    });
                })
                    .listen(port, host, function () {
                    console.log("App listening on port ".concat(port, "!"));
                    console.log("https://local.yunser.com:".concat(port, "/"));
                });
                g_httpsServer = _server;
                return [2 /*return*/, {}];
            });
        });
    };
    SocketService.prototype.http2CreateServer = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, host, _b, port, webSocketId, server;
            return __generator(this, function (_c) {
                _a = body.host, host = _a === void 0 ? '0.0.0.0' : _a, _b = body.port, port = _b === void 0 ? 80 : _b, webSocketId = body.webSocketId;
                server = http2.createSecureServer({
                    key: Buffer.from(fixed_key),
                    cert: Buffer.from(fixed_crt),
                });
                g_http2Server = server;
                server.on('error', function (err) {
                    console.log('on/error');
                    console.error(err);
                });
                server.on('session', function () {
                    console.log('on/session');
                })
                    .on('request', function () {
                    console.log('on/request');
                })
                    .on('stream', function (stream, headers) {
                    console.log('on/stream');
                    // console.log('headers', headers)
                    // const path = headers[':path'];
                    stream.on('close', function () {
                        console.log('The stream is closed');
                    });
                    stream.respond({
                        'content-type': 'text/html; charset=utf-8',
                        ':status': 200
                    });
                    //   stream.pushStream({ [HTTP2_HEADER_PATH]: '/style.css' }, (err, pushStream, headers) => {
                    //     if (err) throw err;
                    //     const fd = fs.openSync('style.css', 'r');
                    //     const stat = fs.fstatSync(fd);
                    //     const header = {
                    //       'content-length': stat.size,
                    //       'last-modified': stat.mtime.toUTCString(),
                    //       'content-type': 'text/css'
                    //     };
                    //     pushStream.respondWithFD(fd, header)
                    //   });
                    stream.end("hello http2");
                    // if (path === '/') {
                    // } else if (path === '/style.css') {
                    //     //   const fd = fs.openSync('style.css', 'r');
                    //     //   const stat = fs.fstatSync(fd);
                    //     //   const headers = {
                    //     //     'content-length': stat.size,
                    //     //     'last-modified': stat.mtime.toUTCString(),
                    //     //     'content-type': 'text/css'
                    //     //   };
                    //     //   stream.respondWithFD(fd, headers);
                    //     stream.end(`
                    //     <h1>Hello World</h1>
                    //     <script>
                    //       setTimeout(()=>{
                    //         fetch('/style.css')
                    //       },2000)
                    //     </script>
                    //   `);
                    // }
                })
                    .on('listening', function () {
                    console.log('http_server/listening');
                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                    (0, ssh_service_1.sendTcpMsg)({
                        webSocketId: webSocketId,
                        message: {
                            type: 'listening',
                            data: {
                                id: (0, uid_1.uid)(8),
                                time: time,
                                // content,
                                // contentType,
                                type: 'listening',
                                port: port,
                                host: host,
                            }
                        }
                    });
                })
                    .on('close', function () {
                    console.log('http_server/close');
                    var time = moment().format('YYYY-MM-DD HH:mm:ss');
                    (0, ssh_service_1.sendTcpMsg)({
                        webSocketId: webSocketId,
                        message: {
                            type: 'close',
                            data: {
                                id: (0, uid_1.uid)(8),
                                time: time,
                                // content,
                                // contentType,
                                type: 'close',
                                // port,
                                // host,
                            }
                        }
                    });
                });
                server.listen(port, host, function () {
                });
                return [2 /*return*/, {}];
            });
        });
    };
    SocketService.prototype.closeHttpServer = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (g_httpServer) {
                    g_httpServer.close();
                }
                return [2 /*return*/];
            });
        });
    };
    SocketService.prototype.closeAllServer = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (g_httpServer) {
                    g_httpServer.close();
                }
                if (g_httpsServer) {
                    g_httpsServer.close();
                    g_httpsServer = null;
                }
                if (g_http2Server) {
                    g_http2Server.close();
                    g_http2Server = null;
                }
                return [2 /*return*/];
            });
        });
    };
    SocketService.prototype.closeHttpsServer = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (g_httpsServer) {
                    g_httpsServer.close();
                }
                return [2 /*return*/];
            });
        });
    };
    SocketService.prototype.closeHttp2Server = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (g_http2Server) {
                    g_http2Server.close();
                    g_http2Server = null;
                }
                return [2 /*return*/];
            });
        });
    };
    SocketService.prototype.websocketConnectionList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var list;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, (0, utils_1.loadDbJson)('websocket.connection.json', [])];
                    case 1:
                        list = _a.sent();
                        return [2 /*return*/, {
                                list: list,
                            }];
                }
            });
        });
    };
    SocketService.prototype.websocketHistoryList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var list;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, (0, utils_1.loadDbJson)('websocket.history.json', [])];
                    case 1:
                        list = _a.sent();
                        return [2 /*return*/, {
                                list: list,
                            }];
                }
            });
        });
    };
    return SocketService;
}());
exports.SocketService = SocketService;
//# sourceMappingURL=socket.service.js.map