/// <summary> /// 发送数据 /// </summary> /// <param name="endpoint"></param> /// <param name="data"></param> /// <returns></returns> public async Task <byte[]> Send(TcpClientEndpoint endpoint, byte[] data) { //初始化终结点 await InitEndpoint(endpoint); TcpClientContext context = null; //从池中获取Tcp客户端上下文 try { context = await _tcpClientContextPool.GetAsync(true); //判断是否已经断开连接,如果已经断开连接,则直接抛出异常 if (context.ConnectionIsClose) { throw context.MainException; } return(await context.Send(data)); } finally { if (context != null) { _tcpClientContextPool.Return(context); } } }
/// <summary> /// 初始化终结点 /// </summary> /// <param name="endpoint"></param> /// <returns></returns> private async Task InitEndpoint(TcpClientEndpoint endpoint) { if (!_start) { _start = true; _endpoint = endpoint; try { _tcpClientContextPool = new Pool <TcpClientContext>($"TcpClient-{endpoint.Name}", null, null, null, null, async() => { TcpClientContext context = new TcpClientContext(endpoint, _loggerFactory, _logCategoryName); await context.Init(); return(context); }, async(context) => { if (context.ConnectionIsClose) { return(await Task.FromResult(false)); } else { try { await context.Send(UTF8Encoding.UTF8.GetBytes(_endpoint.HeartBeatSendData)); } catch (Exception ex) { LoggerHelper.LogError(_logCategoryName, $"TcpClientEndpoint {_endpoint.Name} send HeartBeat error,server address:{_endpoint.ServerAddress},port:{_endpoint.ServerPort.ToString()},error message:{ex.Message},stack:{ex.StackTrace}"); } if (context.ConnectionIsClose) { return(await Task.FromResult(false)); } else { return(await Task.FromResult(true)); } } }, null, null, endpoint.PoolMaxSize ); if (_endpoint.KeepAlive) { //启动一个循环执行的方法,每隔一秒为所有可用的连接发送心跳信息 var t = Task.Run(async() => { while (_start) { await _tcpClientContextPool.InvokeEveryUnUseItem(async(context) => { if (!context.ConnectionIsClose) { try { await context.Send(UTF8Encoding.UTF8.GetBytes(_endpoint.HeartBeatSendData)); } catch (Exception ex) { LoggerHelper.LogError(_logCategoryName, $"TcpClientEndpoint {_endpoint.Name} send HeartBeat error,server address:{_endpoint.ServerAddress},port:{_endpoint.ServerPort.ToString()},error message:{ex.Message},stack:{ex.StackTrace}"); } } }); System.Threading.Thread.Sleep(1000); } }); } } catch { _start = false; throw; } } await Task.FromResult(0); }