private void AsyncReceiveImp() { if (m_socket != null && m_socket.Sockets != null && m_socket.Sockets.Connected) { if (packageBuffSize >= m_receiveBuffer.Length) { log.Error("无可用缓冲区来接收数据."); m_socket.Disconnect(); } else { m_receiveAsyncEvent.SetBuffer(m_receiveBuffer, packageBuffSize, m_receiveBuffer.Length - packageBuffSize); if (!m_socket.Sockets.ReceiveAsync(m_receiveAsyncEvent)) { AsyncReceiveComplete(m_socket.Sockets, m_receiveAsyncEvent); } } } }
private static void SendAsyncImp(object state) { PackageProcessor proc = state as PackageProcessor; ByteSocket s = proc.m_socket; try { AsyncSendPkgComplete(s.Sockets, proc.m_sendAsyncEvent); } catch (Exception ex) { log.Error("Async send package error.", ex); s.Disconnect(); } }
private static void AsyncSendPkgComplete(object sender, SocketAsyncEventArgs e) { PackageProcessor proc = (PackageProcessor)e.UserToken; ByteSocket sock = proc.m_socket; try { Queue q = proc.m_pkgQueue; if (q == null || !sock.Sockets.Connected) { return; } int sent = e.BytesTransferred; byte[] data = proc.m_sendBuffer; int count = proc.m_sendedLength - sent; if (count > 0) { Array.Copy(data, sent, data, 0, count); } else { count = 0; } e.SetBuffer(0, 0); int firstOffset = proc.m_firstPkgOffset; lock (q.SyncRoot) { while (q.Count > 0) { Package pkg = (Package)q.Peek(); int len = 0; if (sock.Encryted) { len = pkg.CopyToEncryt(data, count, firstOffset, sock.PackageCrytor); } else { len = pkg.CopyTo(data, count, firstOffset); } firstOffset += len; count += len; if (pkg.dataLength <= firstOffset) { q.Dequeue(); firstOffset = 0; sock.PackageCrytor.EncrytOnceComplete(); } if (data.Length == count) { break; } } proc.m_firstPkgOffset = firstOffset; if (count <= 0) { proc.m_sendingTcp = false; return; } } proc.m_sendedLength = count; e.SetBuffer(0, count); if (sock.Sockets.SendAsync(e)) { return; } AsyncSendPkgComplete(sender, e); } catch (Exception ex) { log.Error("Async sending package error.", ex); sock.Disconnect(); } }