Beispiel #1
0
        static void ChangeMap(Map map)
        {
            if (MapList == null)
            {
                MapList = new List <Map>();
            }
            switch (map.ChangeType)
            {
            case (int)ChangeMapType.新增:
                MapList.Add(map);
                break;

            case (int)ChangeMapType.修改:
                var item = MapList.Find(c => c.id == map.id);
                if (item != null)
                {
                    item = map;
                }
                else
                {
                    MapList.Add(map);
                }
                break;

            case (int)ChangeMapType.除:
                MapList.RemoveAll(c => c.id == map.id);
                break;
            }
            HandleLog.WriteLine($"映射{Enum.GetName(typeof(ChangeMapType), map.ChangeType)}成功:{JsonHelper.Instance.Serialize(map)}", false);
            HandleLog.WriteLine($"【{map.name}】映射{Enum.GetName(typeof(ChangeMapType), map.ChangeType)}成功:{map.local} --> {map.remote}");
        }
Beispiel #2
0
        /// <summary>
        /// 处理请求
        /// </summary>
        /// <param name="e"></param>
        static void HandleRequest(PackageEventArgs <NatPackageInfo> e)
        {
            Task.Run(() =>
            {
                try
                {
                    var packJson    = JsonHelper.Instance.Deserialize <PackJson>(e.Package.BodyRaw);
                    var headers     = packJson.Headers;
                    var contentType = headers.ContainsKey("Content-Type") ? headers["Content-Type"] : null;
                    var data        = packJson.Content == null ? "" : Encoding.UTF8.GetString(packJson.Content);
                    if (!string.IsNullOrEmpty(contentType))
                    {
                        var index = contentType.IndexOf(";");
                        if (index > 0)
                        {
                            //去掉; charset=utf-8
                            contentType = contentType.Substring(0, index);
                        }
                    }
                    var map = MapList.Find(c => c.remote == packJson.Host);
                    if (map == null)
                    {
                        HandleLog.WriteLine($"映射不存在,外网访问地址:{packJson.Host}");
                        return;
                    }
                    var res = HttpHelper.Request(packJson.Method, $"{map.protocol}://{map.local}{packJson.Route}", data, headers: headers, contentType: contentType);
                    if (res == null)
                    {
                        HandleLog.WriteLine("服务器返回NULL");
                        return;
                    }
                    using (res)
                    {
                        using var stream   = res.Content.ReadAsStreamAsync().Result;
                        var result         = DataHelper.StreamToBytes(stream);
                        var rawResult      = Encoding.UTF8.GetString(result);
                        StringBuilder resp = new StringBuilder();
                        resp.Append($"{map.protocol.ToUpper()}/{res.Version} {(int)res.StatusCode} {res.StatusCode.ToString()}\r\n");
                        foreach (var item in res.Headers)
                        {
                            if (item.Key != "Transfer-Encoding")
                            {
                                resp.Append($"{item.Key}: {string.Join(";", item.Value)}\r\n");
                            }
                        }
                        foreach (var item in res.Content.Headers)
                        {
                            resp.Append($"{item.Key}: {string.Join(";", item.Value)}\r\n");
                        }
                        if (packJson.Method.ToUpper() == "OPTIONS")
                        {
                            resp.Append("Access-Control-Allow-Credentials: true\r\n");
                            if (packJson.Headers.ContainsKey("Access-Control-Request-Headers"))
                            {
                                resp.Append($"Access-Control-Allow-Headers: {packJson.Headers["Access-Control-Request-Headers"]}\r\n");
                            }
                            resp.Append("Access-Control-Allow-Methods: *\r\n");
                            resp.Append($"Access-Control-Allow-Origin: {packJson.Headers["Origin"]}\r\n");
                        }
                        if (!res.Content.Headers.Contains("Content-Length"))
                        {
                            resp.Append($"Content-Length: {result.Length}\r\n");
                        }
                        resp.Append($"Date: {DateTime.Now}\r\n");
                        resp.Append("Connection:close\r\n\r\n");

                        var response = Encoding.UTF8.GetBytes(resp.ToString()).ToList();
                        response.AddRange(result);

                        //先gzip压缩  再转为16进制字符串
                        var body = DataHelper.Compress(response.ToArray());
                        var pack = new PackJson()
                        {
                            Host         = packJson.Host,
                            UserId       = packJson.UserId,
                            Content      = body,
                            ResponseInfo = $"{map.name} {packJson.Method} {packJson.Route} {(int)res.StatusCode} {res.StatusCode.ToString()}"
                        };
                        var json      = JsonHelper.Instance.Serialize(pack);
                        var jsonBytes = Encoding.UTF8.GetBytes(json);
                        //请求头 01 03 长度(4)
                        var sendBytes = new List <byte>()
                        {
                            0x1, 0x3
                        };
                        sendBytes.AddRange(BitConverter.GetBytes(jsonBytes.Length).Reverse());
                        sendBytes.AddRange(jsonBytes);
                        NatClient.Send(sendBytes.ToArray());
                        HandleLog.WriteLine(pack.ResponseInfo);
                    }
                }
                catch (Exception ex)
                {
                    HandleLog.WriteLine($"处理请求异常:{ex}");
                }
            });
        }