private static void ReadTcp_Server(IAsyncResult ar) { RelationTcp_Server relation = (RelationTcp_Server)ar.AsyncState; if (relation.guid == EasyInject.Get <AppCenter>().CurrentGuid) { if (relation.readTcp.Connected && relation.readTcp.GetStream().CanRead) { int length = 0; EasyOp.Do(() => { length = relation.readTcp.GetStream().EndRead(ar); }, () => { if (length > 0) { byte[] refData = relation.buffer.Take(length).ToArray(); while (relation.msgReceive.ParseData(ref refData)) { // 执行command using (P2PCommand command = FindCommand(relation.readTcp, relation.msgReceive)) { //LogUtils.Trace($"命令类型:{relation.msgReceive.CommandType}"); if (command != null) { bool isSuccess = false; EasyOp.Do(() => { isSuccess = command.Excute(); }, e => { LogUtils.Error($"执行命令{relation.msgReceive.CommandType}时发生异常:{e}"); }); if (!isSuccess) { EasyOp.Do(() => { relation.readTcp?.SafeClose(); }); EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); }); return; } } else { EasyOp.Do(() => { relation.readTcp?.SafeClose(); }); EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); }); return; } } //重置msgReceive relation.msgReceive.Reset(); if (refData.Length <= 0) { break; } } if (relation.readTcp.Connected) { EasyOp.Do(() => { relation.readTcp.GetStream().BeginRead(relation.buffer, 0, relation.buffer.Length, ReadTcp_Server, relation); }, ex => { LogUtils.Debug($"Tcp连接已被断开 {relation.readTcp.RemoteEndPoint}"); EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); }); }); } } else { EasyOp.Do(() => { relation.readTcp?.SafeClose(); }); EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); }); } }, ex => { LogUtils.Debug($"Tcp连接已被断开 {relation.readTcp.RemoteEndPoint}"); EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); }); }); } } else { LogUtils.Debug($"主动断开{relation.readTcp.RemoteEndPoint}连接"); EasyOp.Do(() => { relation.readTcp?.SafeClose(); }); EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); }); } //if (TcpCenter.Instance.ConnectedTcpList.Contains(relation.readTcp)) // TcpCenter.Instance.ConnectedTcpList.Remove(relation.readTcp); }
private void ListenPortMapPortWithServerName(PortMapItem item) { TcpListener listener = new TcpListener(IPAddress.Any, item.LocalPort); try { listener.Start(); } catch (Exception ex) { LogUtils.Error($"【失败】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.ToString()}"); return; } ListenerList.Add(listener); LogUtils.Show($"【成功】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); Global.TaskFactory.StartNew(() => { TcpManage tcpManage = null; if (item.RemotePort == 3389) { tcpManage = new TcpManage(6); } while (true) { Socket socket = listener.AcceptSocket(); string remoteAddress = ((IPEndPoint)socket.RemoteEndPoint).Address.ToString(); if (tcpManage != null) { tcpManage.AddTcp(remoteAddress); if (!tcpManage.IsAllowConnect(remoteAddress)) { LogUtils.Show($"【安全策略】阻止内网穿透:{remoteAddress}->{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); socket.Close(); continue; } } LogUtils.Show($"开始内网穿透:{remoteAddress}->{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); P2PTcpClient tcpClient = new P2PTcpClient(socket); Global.TaskFactory.StartNew(() => { string token = tcpClient.Token; //获取目标tcp if (Global.TcpMap.ContainsKey(item.RemoteAddress) && Global.TcpMap[item.RemoteAddress].TcpClient.Connected) { //加入待连接集合 Global.WaiteConnetctTcp.Add(token, tcpClient); //发送p2p申请 Models.Send.Send_0x0211 packet = new Models.Send.Send_0x0211(token, item.RemotePort, tcpClient.RemoteEndPoint); Global.TcpMap[item.RemoteAddress].TcpClient.Client.Send(packet.PackData()); Global.TaskFactory.StartNew(() => { Thread.Sleep(Global.P2PTimeout); //如果5秒后没有匹配成功,则关闭连接 if (Global.WaiteConnetctTcp.ContainsKey(token)) { LogUtils.Warning($"【失败】内网穿透:{Global.P2PTimeout}秒无响应,已超时."); Global.WaiteConnetctTcp[token].Close(); Global.WaiteConnetctTcp.Remove(token); } }); } else { LogUtils.Warning($"【失败】内网穿透:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort} 客户端不在线!"); tcpClient.Close(); } }); } }); }
public static void ListenTcp <T>(P2PTcpClient tcpClient) where T : ReceivePacket { try { Guid curGuid = AppCenter.Instance.CurrentGuid; byte[] buffer = new byte[P2PGlobal.P2PSocketBufferSize]; NetworkStream tcpStream = tcpClient.GetStream(); tcpClient.ReceiveBufferSize = P2PGlobal.P2PSocketBufferSize; ReceivePacket msgReceive = Activator.CreateInstance(typeof(T)) as ReceivePacket; int maxTotal = 1024 * 50 * 2; int[] recieveLength = new int[2]; int lastSecond = -1; while (tcpClient.Connected && curGuid == AppCenter.Instance.CurrentGuid) { int curReadLength = tcpStream.ReadSafe(buffer, 0, buffer.Length); if (curReadLength > 0) { byte[] refData = buffer.Take(curReadLength).ToArray(); if (tcpClient.IsSpeedLimit) { int curSecond = DateTime.Now.Second; if (DateTime.Now.Second != lastSecond) { recieveLength[curSecond % 2] = 0; } lastSecond = curSecond; recieveLength[curSecond % 2] += curReadLength; if (recieveLength.Sum() > maxTotal) { Thread.Sleep(1000); } } while (msgReceive.ParseData(ref refData)) { LogUtils.Debug($"命令类型:{msgReceive.CommandType}"); // 执行command using (P2PCommand command = FindCommand(tcpClient, msgReceive)) { command?.Excute(); } //重置msgReceive msgReceive.Reset(); if (refData.Length <= 0) { break; } } } else { break; } } } catch (Exception ex) { LogUtils.Error($"【错误】Global_Func.ListenTcp:{Environment.NewLine}{ex}"); } if (ClientCenter.Instance.TcpMap.ContainsKey(tcpClient.ClientName)) { if (ClientCenter.Instance.TcpMap[tcpClient.ClientName].TcpClient == tcpClient) { ClientCenter.Instance.TcpMap.Remove(tcpClient.ClientName); } } //如果tcp已关闭,需要关闭相关tcp try { tcpClient.ToClient?.SafeClose(); } catch { } LogUtils.Debug($"tcp连接{tcpClient.RemoteEndPoint}已断开"); }