public static SocketAwaitable ReceiveAsync(this Socket socket, SocketAwaitable awaitable) { awaitable.Reset(); if (!socket.ReceiveAsync(awaitable.m_eventArgs)) { awaitable.m_wasCompleted = true; } return(awaitable); }
async Task ReadAsync(Socket s) { // Reusable SocketAsyncEventArgs and awaitable wrapper var args = new SocketAsyncEventArgs(); args.SetBuffer(new byte[0x100000], 0, 0x100000); var awaitable = new SocketAwaitable(args); while (_isInit) { await s.ReceiveAsync(awaitable); int bytesRead = args.BytesTransferred; if (bytesRead <= 0) { throw new Exception("Raw socket is disconnected"); } IPv4Packet ipPacket; try { ipPacket = new IPv4Packet(new ByteArraySegment(args.Buffer, 0, bytesRead)); } catch (InvalidOperationException) { continue; } if (ipPacket.Version != IpVersion.IPv4 || ipPacket.Protocol != IPProtocolType.TCP) { continue; } OnPacketReceived(ipPacket); } _socket.Close(); _socket = null; }