private void ReceiveCompleted(object sender, SocketAsyncEventArgs e) { if (e.BytesTransferred == 0 || e.SocketError != SocketError.Success) { if (_disposed != 1) { Logger?.Log(LogLevels.Error, () => $"cannot receive tcp: {e.SocketError}"); } ReconnectImpl(); return; } var available = e.Offset + e.BytesTransferred; for (;;) { var offset = 0; var result = _packetContract.TryParse(e.Buffer, ref offset, available, out var packet); if (result.Code == ParseResult.ResultCodes.NeedMoreData) { break; } if (result.Code == ParseResult.ResultCodes.BoxIsBroken) { if (_disposed != 1) { Logger?.Log(LogLevels.Error, () => "cannot receive tcp: buffer discarded"); } ConnectImpl(); return; } available -= offset; if (packet != null) { ReceivePacket?.Invoke(this, packet); } Array.Copy(e.Buffer, offset, e.Buffer, 0, available); } var buffer = e.Buffer; if (available == buffer.Length) { Array.Resize(ref buffer, buffer.Length * 2); } e.SetBuffer(buffer, available, buffer.Length - available); ReceiveImpl(); }
private void ReceiveCompleted(object sender, SocketAsyncEventArgs e) { if (e.BytesTransferred == 0 || e.SocketError != SocketError.Success) { if (_disposed != 1) { Logger?.Log(LogLevels.Error, () => $"cannot receive udp: {e.SocketError}"); } ReceiveImpl(); return; } var offset = e.Offset; var result = _packetContract.TryParse(e.Buffer, ref offset, e.Offset + e.BytesTransferred, out var packet); ReceivePacket?.Invoke(this, new PacketContainer <T> { Source = (IPEndPoint)e.RemoteEndPoint, Target = new IPEndPoint(e.ReceiveMessageFromPacketInfo.Address, Port), Payload = packet, }); ReceiveImpl(); }