private static void OnSend(object sender, SocketAsyncEventArgs e) { //Console.WriteLine("OnSend e.ToString():=[" + e.ToString() + "]"); if (e == null) { return; } if (e.LastOperation != SocketAsyncOperation.Send) { return; } if (e.SocketError != SocketError.Success) { //-- log return; } OnSendObj sendObj = e.UserToken as OnSendObj; if (sendObj == null) { return; } if (sendObj.m_SendBuffer == null) { return; } if (sendObj.m_TSocket == null) { return; } if (e.BytesTransferred > 0) { sendObj.m_SendBuffer.AddTransferByteNum(e.BytesTransferred); if (!sendObj.m_SendBuffer.IsFinished()) { sendObj.m_TSocket.Send(sendObj.m_SendBuffer); //-- test MemoryStream memStream = sendObj.m_SendBuffer.GetMemoryStream(); if (memStream != null) { //Console.WriteLine("Send bytes continue:=[" + e.BytesTransferred + "] content:=[" + memStream.GetBuffer().ToString() + "]"); } } else { sendObj.m_SendBuffer.SetEmptyFlag(true); //-- test MemoryStream memStream = sendObj.m_SendBuffer.GetMemoryStream(); if (memStream != null) { //Console.WriteLine("Send bytes successed:=[" + e.BytesTransferred + "] content:=[" + memStream.GetBuffer().ToString() + "]"); } } } //-- reuse e.Dispose(); return; }
private bool Send(SocketSendBuf sendBuff) { if (sendBuff == null) { return(false); } MemoryStream sendMemStream = sendBuff.GetMemoryStream(); if (sendMemStream == null) { return(false); } if (sendMemStream.Length == 0) { return(true); } if (sendBuff.IsFinished()) { return(true); } //-- 异步将发送缓冲区数据发送出去。 OnSendObj sendObj = new OnSendObj(); sendObj.m_SendBuffer = sendBuff; sendObj.m_TSocket = this; SocketAsyncEventArgs sendCompleteArgs = new SocketAsyncEventArgs(); sendCompleteArgs.RemoteEndPoint = m_IPAndPoint; sendCompleteArgs.UserToken = sendObj; sendCompleteArgs.Completed += new EventHandler <SocketAsyncEventArgs>(OnSend); try { //-- 下面的以后放在一个pool中。 byte[] tmpbyteArray = new byte[(int)sendMemStream.Length]; Array.Copy(sendMemStream.GetBuffer(), tmpbyteArray, (int)sendMemStream.Length); sendCompleteArgs.SetBuffer(tmpbyteArray, 0, tmpbyteArray.Length); //sendCompleteArgs.SetBuffer(sendMemStream.GetBuffer(), sendBuff.GetTransferByteNum(), (int)sendMemStream.Length); //-- test log //Console.WriteLine("sendMemStream.Length:==[" + sendMemStream.Length + "]"); } catch (System.Exception ex) { //-- log CommonDebugLog.LogWarning("ex:=[" + ex.ToString() + "]"); return(false); } //-: true,io pend. waiting callback try { if (!m_Socket.SendAsync(sendCompleteArgs)) { OnSend(null, sendCompleteArgs); } } catch (System.Exception ex) { CommonDebugLog.LogWarning("ex:=[" + ex.ToString() + "]"); } return(true); }