예제 #1
0
 public void OnPackageReceived(object sender, PackageEventArgs <ClientPackageInfo> e)
 {
     Task.Run(() =>
     {
         //先gzip压缩  再转为16进制字符串
         var body = DataHelper.Compress(e.Package.Data);
         var pack = new PackJson()
         {
             Host    = PackJson.Host,
             UserId  = PackJson.UserId,
             Content = body
         };
         var json      = JsonHelper.Instance.Serialize(pack);
         var jsonBytes = Encoding.UTF8.GetBytes(json);
         //03 02 数据长度(4) 正文数据(n)   ---tcp响应包
         var sendBytes = new List <byte>()
         {
             0x3, 0x2
         };
         sendBytes.AddRange(BitConverter.GetBytes(jsonBytes.Length).Reverse());
         sendBytes.AddRange(jsonBytes);
         //转发给服务器
         NatClient.Send(sendBytes.ToArray());
         HandleLog.WriteLine($"<---- {PackJson.UserId} 收到报文{e.Package.Data.Length}字节");
     });
 }
예제 #2
0
        private static void TcpServer_NewSessionConnected(TcpAppSession session)
        {
            try
            {
                //转发请求
                var natSession = NATServer.GetSessions(c => c.MapList?.Any(m => m.remote_port == session.LocalEndPoint.Port) ?? false).FirstOrDefault();
                if (natSession == null)
                {
                    session?.Close();
                    HandleLog.WriteLine($"请求:{session.LocalEndPoint}失败,Nat客户端连接不在线!");
                    return;
                }
                var map = natSession.MapList?.Find(c => c.remote_port == session.LocalEndPoint.Port);
                if (map == null)
                {
                    session?.Close();
                    HandleLog.WriteLine($"请求:{session.LocalEndPoint}失败,映射{session.LocalEndPoint}不存在!");
                    return;
                }
                session.Map = map;
                var pack = new PackJson()
                {
                    Host   = map?.remote_endpoint,
                    Local  = map?.local_endpoint,
                    UserId = session.UserId,
                    Method = "TCP"
                };
                session.PackJson = pack;
                var json      = JsonHelper.Instance.Serialize(pack);
                var jsonBytes = Encoding.UTF8.GetBytes(json);
                //03 01 数据长度(4) 正文数据(n)   ---tcp连接注册包
                var sendBytes = new List <byte>()
                {
                    0x3, 0x1
                };
                sendBytes.AddRange(BitConverter.GetBytes(jsonBytes.Length).Reverse());
                sendBytes.AddRange(jsonBytes);
                natSession.Send(sendBytes.ToArray(), 0, sendBytes.Count);

                session.NatSession = natSession;
                HandleLog.WriteLine($"客户端【{session.PackJson.UserId},{session.RemoteEndPoint}】已连接【{session.LocalEndPoint}】");
            }
            catch (Exception ex)
            {
                HandleLog.WriteLine($"连接【{session.PackJson.UserId},{session.LocalEndPoint}】发生异常:{ex}");
            }
        }
예제 #3
0
 private static void WebServer_NewRequestReceived(WebAppSession session, HttpRequestInfo requestInfo)
 {
     Task.Run(() =>
     {
         try
         {
             if (session.RequestTime == null)
             {
                 session.RequestTime = DateTime.Now;
             }
             //转发请求
             var host       = requestInfo.HeaderDict["Host"];
             var natSession = NATServer.GetSessions(c => c.MapList?.Any(m => m.remote_endpoint == host) ?? false).FirstOrDefault();
             if (natSession == null)
             {
                 session?.Close();
                 HandleLog.WriteLine($"请求:{host}失败,Nat客户端连接不在线!");
                 return;
             }
             var pack = new PackJson()
             {
                 Host    = host,
                 UserId  = session.UserId,
                 Method  = requestInfo.Method,
                 Route   = requestInfo.Route,
                 Headers = requestInfo.HeaderDict,
                 Content = requestInfo.Content
             };
             var json      = JsonHelper.Instance.Serialize(pack);
             var jsonBytes = Encoding.UTF8.GetBytes(json);
             //02 01 数据长度(4) 正文数据(n)   ---http响应包
             var sendBytes = new List <byte>()
             {
                 0x2, 0x1
             };
             sendBytes.AddRange(BitConverter.GetBytes(jsonBytes.Length).Reverse());
             sendBytes.AddRange(jsonBytes);
             natSession.Send(sendBytes.ToArray(), 0, sendBytes.Count);
         }
         catch (Exception ex)
         {
             HandleLog.WriteLine($"【{session.RemoteEndPoint}】请求参数:{Encoding.UTF8.GetString(requestInfo.Data)},处理发生异常:{ex}");
         }
     });
 }
예제 #4
0
        public static void CloseLocalClient(TcpAppSession session)
        {
            var pack = new PackJson()
            {
                Host   = session.PackJson.Host,
                UserId = session.PackJson.UserId
            };
            var json      = JsonHelper.Instance.Serialize(pack);
            var jsonBytes = Encoding.UTF8.GetBytes(json);
            //03 03 数据长度(4) 正文数据(n)   ---tcp连接关闭包
            var sendBytes = new List <byte>()
            {
                0x3, 0x3
            };

            sendBytes.AddRange(BitConverter.GetBytes(jsonBytes.Length).Reverse());
            sendBytes.AddRange(jsonBytes);
            //转发给客户端
            session.NatSession?.Send(sendBytes.ToArray());
        }
예제 #5
0
        public void CloseRemouteClient()
        {
            var pack = new PackJson()
            {
                Host   = PackJson.Host,
                UserId = PackJson.UserId
            };
            var json      = JsonHelper.Instance.Serialize(pack);
            var jsonBytes = Encoding.UTF8.GetBytes(json);
            //03 03 数据长度(4) 正文数据(n)   ---tcp连接关闭包
            var sendBytes = new List <byte>()
            {
                0x3, 0x3
            };

            sendBytes.AddRange(BitConverter.GetBytes(jsonBytes.Length).Reverse());
            sendBytes.AddRange(jsonBytes);
            //转发给服务器
            NatClient.Send(sendBytes.ToArray());
        }
예제 #6
0
 private static void TcpServer_NewRequestReceived(TcpAppSession session, TcpRequestInfo requestInfo)
 {
     Task.Run(() =>
     {
         try
         {
             while (session.NatSession == null)
             {
                 Thread.Sleep(50);
             }
             //先gzip压缩  再转为16进制字符串
             var body = DataHelper.Compress(requestInfo.Data);
             var pack = new PackJson()
             {
                 Host    = session.Map?.remote_endpoint,
                 Local   = session.Map?.local_endpoint,
                 UserId  = session.UserId,
                 Method  = "TCP",
                 Content = body
             };
             var json      = JsonHelper.Instance.Serialize(pack);
             var jsonBytes = Encoding.UTF8.GetBytes(json);
             //03 02 数据长度(4) 正文数据(n)   ---tcp响应包
             var sendBytes = new List <byte>()
             {
                 0x3, 0x2
             };
             sendBytes.AddRange(BitConverter.GetBytes(jsonBytes.Length).Reverse());
             sendBytes.AddRange(jsonBytes);
             session.NatSession.Send(sendBytes.ToArray(), 0, sendBytes.Count);
             HandleLog.WriteLine($"<---- {session.PackJson.UserId} 收到报文{requestInfo.Data.Length}字节");
         }
         catch (Exception ex)
         {
             HandleLog.WriteLine($"【{session.LocalEndPoint}】请求参数:{Encoding.UTF8.GetString(requestInfo.Data)},处理发生异常:{ex}");
         }
     });
 }
예제 #7
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}");
                }
            });
        }
예제 #8
0
 public TcpClientInfo(PackJson packJson, EasyClient <NatPackageInfo> natClient)
 {
     PackJson  = packJson;
     NatClient = natClient;
     Init();
 }