/// <summary> /// Send the data, whose size should less than or equal to OutgoingBufferSize in bytes. /// </summary> /// <param name="data">Data.</param> /// <param name="throwExceptionOnFail"></param> public async Task <bool> Send(ClientOutputBuffer data, bool throwExceptionOnFail = false) { if (Disconnected || data.m_dataLen == 0) { return(false); } bool sendOk = true; try { //Log.Info("发送一条消息 Count = " + data.m_dataLen); await m_tcpClient.GetStream().WriteAsync(data.m_buffer, 0, data.m_dataLen, m_cancellationToken); } catch (Exception) { if (throwExceptionOnFail) { throw; } //Console.WriteLine("Client.Send Exception! MsgId = {0}, Error={1} time={2} BufferCount={3}", BitConverter.ToInt32(data._buffer, sizeof(Int32)), ex.Message, DateTime.Now.ToString(), ClientOutputBuffer.PoolBuffCount); sendOk = false; } finally { //将buff放入缓存队列中 ClientOutputBuffer.UnlockSendBuffer(data); } ///Log.Info($"发送一条消息 {sendOk} "); return(sendOk); }
/// <summary> /// 解锁 /// </summary> /// <param name="buf"></param> public static void UnlockSendBuffer(ClientOutputBuffer buf) { //如果当前池子的buff过多就清理一次缓存 if (m_outputBufferPool.Count > m_maxPoolLength) { if ((DateTime.Now - m_lastLockTime).TotalMinutes > m_maxPoolFreeWaitMinutes) { // 清理数据 ClientOutputBuffer outBuf = null; while (m_outputBufferPool.Count > m_maxPoolLength) { m_outputBufferPool.TryPop(out outBuf); } } } buf.m_dataLen = 0; m_outputBufferPool.Push(buf); }
/// <summary> /// [ThreadSafe] /// 获取buf /// </summary> public static ClientOutputBuffer LockSendBuffer(int size) { if (!m_outputBufferPool.TryPop(out var buf)) { buf = new ClientOutputBuffer(size); m_lastLockTime = DateTime.Now; } else { //如果池子里没有则 新生成一个 如果长度不够,重新分配一下 if (buf.m_maxLen < size) { Array.Resize(ref buf.m_buffer, size); buf.m_maxLen = size; } } if (m_outputBufferPool.Count == 0) { m_lastLockTime = DateTime.Now; } return(buf); }