Example #1
0
		public TestByteBuffer(byte[] buffer)
		{
			if (_useLegacyImplementation)
				_bb = new LegacyByteBuffer(CopyBytes(buffer));
			else
				_bb = new ByteBuffer(CopyBytes(buffer), _useHighCapacityMode);
		}
Example #2
0
		public TestByteBuffer()
		{
			if (_useLegacyImplementation)
				_bb = new LegacyByteBuffer();
			else
				_bb = new ByteBuffer(_useHighCapacityMode);
		}
 public EchoClientHandler()
 {
     this.buffer = new byte[EchoClientSettings.Size];
     this.initialMessage = Unpooled.Buffer(EchoClientSettings.Size);
     byte[] messageBytes = Encoding.UTF8.GetBytes("Hello world");
     this.initialMessage.WriteBytes(messageBytes);
 }
Example #4
0
        public static IByteBuffer YbrFull422ToRgb(IByteBuffer data)
        {
            byte[] oldPixels = data.Data;
            byte[] newPixels = new byte[(oldPixels.Length / 4) * 2 * 3];

            unchecked
            {
                int y1, y2, cb, cr;
                for (int n = 0, p = 0; n < oldPixels.Length;)
                {
                    y1 = oldPixels[n++];
                    y2 = oldPixels[n++];
                    cb = oldPixels[n++];
                    cr = oldPixels[n++];

                    newPixels[p++] = (byte)(y1 + 1.4020 * (cr - 128) + 0.5);
                    newPixels[p++] = (byte)(y1 - 0.3441 * (cb - 128) - 0.7141 * (cr - 128) + 0.5);
                    newPixels[p++] = (byte)(y1 + 1.7720 * (cb - 128) + 0.5);

                    newPixels[p++] = (byte)(y2 + 1.4020 * (cr - 128) + 0.5);
                    newPixels[p++] = (byte)(y2 - 0.3441 * (cb - 128) - 0.7141 * (cr - 128) + 0.5);
                    newPixels[p++] = (byte)(y2 + 1.7720 * (cb - 128) + 0.5);
                }
            }

            return new MemoryByteBuffer(newPixels);
        }
 public DuplicatedByteBuffer(IByteBuffer source)
     : base(source.MaxCapacity)
 {
     var asDuplicate = source as DuplicatedByteBuffer;
     this.buffer = asDuplicate != null ? asDuplicate.buffer : source;
     this.SetIndex(source.ReaderIndex, source.WriterIndex);
 }
 protected static IByteBuffer ToLeakAwareBuffer(IByteBuffer buf)
 {
     IResourceLeak leak;
     switch (ResourceLeakDetector.Level)
     {
         case ResourceLeakDetector.DetectionLevel.Simple:
             leak = AbstractByteBuffer.LeakDetector.Open(buf);
             if (leak != null)
             {
                 buf = new SimpleLeakAwareByteBuffer(buf, leak);
             }
             break;
         case ResourceLeakDetector.DetectionLevel.Advanced:
         case ResourceLeakDetector.DetectionLevel.Paranoid:
             leak = AbstractByteBuffer.LeakDetector.Open(buf);
             if (leak != null)
             {
                 buf = new AdvancedLeakAwareByteBuffer(buf, leak);
             }
             break;
         case ResourceLeakDetector.DetectionLevel.Disabled:
             break;
         default:
             throw new ArgumentOutOfRangeException();
     }
     return buf;
 }
Example #7
0
        public SlicedByteBuffer(IByteBuffer buffer, int index, int length)
            : base(length)
        {
            if (index < 0 || index > buffer.Capacity - length)
            {
                throw new ArgumentOutOfRangeException("index", buffer + ".slice(" + index + ", " + length + ')');
            }

            var slicedByteBuf = buffer as SlicedByteBuffer;
            if (slicedByteBuf != null)
            {
                this.buffer = slicedByteBuf.buffer;
                this.adjustment = slicedByteBuf.adjustment + index;
            }
            else if (buffer is DuplicatedByteBuffer)
            {
                this.buffer = buffer.Unwrap();
                this.adjustment = index;
            }
            else
            {
                this.buffer = buffer;
                this.adjustment = index;
            }
            this.length = length;

            this.SetWriterIndex(length);
        }
        public static async Task ReadBytesAsync(this Stream stream, IByteBuffer buffer, int offset, int count, CancellationToken cancellationToken)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (count < 0 || offset + count > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("count");
            }

            while (count > 0)
            {
                var backingBytes = buffer.AccessBackingBytes(offset);
                var bytesToRead = Math.Min(count, backingBytes.Count);
                var bytesRead = await stream.ReadAsync(backingBytes.Array, backingBytes.Offset, bytesToRead, cancellationToken).ConfigureAwait(false);
                if (bytesRead == 0)
                {
                    throw new EndOfStreamException();
                }
                offset += bytesRead;
                count -= bytesRead;
            }
        }
Example #9
0
        internal static void WriteStringToBuffer(IByteBuffer buffer, string input)
        {
            int typeBytes = Encoding.UTF8.GetByteCount(input);

            buffer.WriteByte(typeBytes);
            buffer.WriteBytes(Encoding.UTF8.GetBytes(input));
        }
Example #10
0
 public DicomReaderEventArgs(long position, DicomTag tag, DicomVR vr, IByteBuffer data)
 {
     Position = position;
     Tag = tag;
     VR = vr;
     Data = data;
 }
Example #11
0
        int IEventHandler.Peek(BufferedSocket bufferedSocket, IByteBuffer msg, ref EndPoint ep)
        {
            Contract.Requires(ep != null);
            //Contract.Requires(bufferedSocket != null);

            return default(int);
        }
Example #12
0
        int IEventHandler.Read(BufferedSocket socket, IByteBuffer msg, ref EndPoint ep)
        {
            //Contract.Requires(socket != null);
            Contract.Requires(msg != null);
            Contract.Requires(ep != null);

            return default(int);
        }
 static IByteBuffer UnwrapIfNeeded(IByteBuffer buf)
 {
     if (buf is AdvancedLeakAwareByteBuffer || buf is SimpleLeakAwareByteBuffer)
     {
         return buf.Unwrap();
     }
     return buf;
 }
 protected internal sealed override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output)
 {
     object decode = this.Decode(context, input);
     if (decode != null)
     {
         output.Add(decode);
     }
 }
 public DeviceStream(SystemServices systemServices)
 {
     Stream = null;
     ByteBuffer = null;
     SystemServices = systemServices;
     DeviceError = false;
     // use new synchronous byte buffer
     GenThreadManager = null;
 }
        // constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="LazyBsonDocument"/> class.
        /// </summary>
        /// <param name="slice">The slice.</param>
        /// <exception cref="System.ArgumentNullException">slice</exception>
        /// <exception cref="System.ArgumentException">LazyBsonDocument cannot be used with an IByteBuffer that needs disposing.</exception>
        public LazyBsonDocument(IByteBuffer slice)
        {
            if (slice == null)
            {
                throw new ArgumentNullException("slice");
            }

            _slice = slice;
        }
 public DeviceStream(GenThreadManagement.GenThreadManager genThreadManager, SystemServices systemServices)
 {
     Stream = null;
     ByteBuffer = null;
     SystemServices = systemServices;
     DeviceError = false;
     // use original threaded byte buffer
     GenThreadManager = genThreadManager;
 }
        // constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="RawBsonArray"/> class.
        /// </summary>
        /// <param name="slice">The slice.</param>
        /// <exception cref="System.ArgumentNullException">slice</exception>
        /// <exception cref="System.ArgumentException">RawBsonArray cannot be used with an IByteBuffer that needs disposing.</exception>
        public RawBsonArray(IByteBuffer slice)
        {
            if (slice == null)
            {
                throw new ArgumentNullException("slice");
            }

            _slice = slice;
        }
Example #19
0
 /// <summary>
 ///  Returns {@code true} if and only if the two specified buffers are
 ///  identical to each other as described in {@link ByteBuf#equals(Object)}.
 ///  This method is useful when implementing a new buffer type.
 /// </summary>
 public static bool Equals(IByteBuffer bufferA, IByteBuffer bufferB)
 {
     int aLen = bufferA.ReadableBytes;
     if (aLen != bufferB.ReadableBytes)
     {
         return false;
     }
     return Equals(bufferA, bufferA.ReaderIndex, bufferB, bufferB.ReaderIndex, aLen);
 }
        // constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="ByteBufferStream"/> class.
        /// </summary>
        /// <param name="buffer">The buffer.</param>
        /// <param name="ownsBuffer">Whether the stream owns the buffer and should Dispose it when done.</param>
        public ByteBufferStream(IByteBuffer buffer, bool ownsBuffer = false)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            _buffer = buffer;
            _ownsBuffer = ownsBuffer;
            _length = buffer.Length;
        }
 public static async Task WriteBufferAsync(this Stream stream, IByteBuffer buffer, int offset, int count, CancellationToken cancellationToken)
 {
     while (count > 0)
     {
         var backingBytes = buffer.AccessBackingBytes(offset);
         var bytesToWrite = Math.Min(count, backingBytes.Count - backingBytes.Offset);
         await stream.WriteAsync(backingBytes.Array, backingBytes.Offset, bytesToWrite, cancellationToken);
         offset += bytesToWrite;
         count -= bytesToWrite;
     }
 }
Example #22
0
 public void sendBlock(IByteBuffer data, Response response)
 {
     int sendId = getNextId();
     IByteBuffer message = ByteBufferManager.Instance.GetObj();
     int pos = data.getReadPos();
     message.writeByte(data.readByte());
     message.writeInt(sendId);
     message.writeByteBuffer(data, data.available());
     data.setReadPos(pos);
     responses[sendId] = response;
     con.send(message);
 }
Example #23
0
 public void Return(IByteBuffer byteBuffer)
 {
     if (byteBuffer is ByteBufferSlab)
     {
         _manager.Return(byteBuffer as ByteBufferSlab);
         return;
     }
     if (byteBuffer is TrackedByteBufferArray)
     {
         _allocated--;
     }
 }
Example #24
0
 public void OnElement(IByteSource source, DicomTag tag, DicomVR vr, IByteBuffer data)
 {
     _log.Log(
         _level,
         "{marker:x8}: {padding}{tag} {vrCode} {tagDictionaryEntryName} [{size}]",
         source.Marker,
         _pad,
         tag,
         vr.Code,
         tag.DictionaryEntry.Name,
         data.Size);
 }
Example #25
0
        /// <summary>
        ///  Returns {@code true} if and only if the two specified buffers are
        ///  identical to each other for {@code length} bytes starting at {@code aStartIndex}
        ///  index for the {@code a} buffer and {@code bStartIndex} index for the {@code b} buffer.
        ///  A more compact way to express this is:
        ///  <p>
        ///  {@code a[aStartIndex : aStartIndex + length] == b[bStartIndex : bStartIndex + length]}
        /// </summary>
        public static bool Equals(IByteBuffer a, int aStartIndex, IByteBuffer b, int bStartIndex, int length)
        {
            if (aStartIndex < 0 || bStartIndex < 0 || length < 0)
            {
                throw new ArgumentException("All indexes and lengths must be non-negative");
            }
            if (a.WriterIndex - length < aStartIndex || b.WriterIndex - length < bStartIndex)
            {
                return false;
            }

            int longCount = unchecked((int)((uint)length >> 3));
            int byteCount = length & 7;

            if (a.Order == b.Order)
            {
                for (int i = longCount; i > 0; i --)
                {
                    if (a.GetLong(aStartIndex) != b.GetLong(bStartIndex))
                    {
                        return false;
                    }
                    aStartIndex += 8;
                    bStartIndex += 8;
                }
            }
            else
            {
                for (int i = longCount; i > 0; i --)
                {
                    if (a.GetLong(aStartIndex) != SwapLong(b.GetLong(bStartIndex)))
                    {
                        return false;
                    }
                    aStartIndex += 8;
                    bStartIndex += 8;
                }
            }

            for (int i = byteCount; i > 0; i --)
            {
                if (a.GetByte(aStartIndex) != b.GetByte(bStartIndex))
                {
                    return false;
                }
                aStartIndex ++;
                bStartIndex ++;
            }

            return true;
        }
Example #26
0
        public SwappedByteBuffer(IByteBuffer buf)
        {
            Contract.Requires(buf != null);

            this.buf = buf;
            if (buf.Order == ByteOrder.BigEndian)
            {
                this.Order = ByteOrder.LittleEndian;
            }
            else
            {
                this.Order = ByteOrder.BigEndian;
            }
        }
		/// <summary>
		/// Convert 24 bits pixels from planar (RRR...GGG...BBB...) to interleaved (RGB)
		/// </summary>
		/// <param name="data">Pixels data in planar format (RRR...GGG...BBB...)</param>
		/// <returns>Pixels data in interleaved format (RGB)</returns>
		public static IByteBuffer PlanarToInterleaved24(IByteBuffer data) {
			byte[] oldPixels = data.Data;
			byte[] newPixels = new byte[oldPixels.Length];
			int pixelCount = newPixels.Length / 3;

			unchecked {
				for (int n = 0; n < pixelCount; n++) {
					newPixels[(n * 3) + 0] = oldPixels[n + (pixelCount * 0)];
					newPixels[(n * 3) + 1] = oldPixels[n + (pixelCount * 1)];
					newPixels[(n * 3) + 2] = oldPixels[n + (pixelCount * 2)];
				}
			}
			
			return new MemoryByteBuffer(newPixels);
		}
 public static async Task FillBufferAsync(this Stream stream, IByteBuffer buffer, int offset, int count, CancellationToken cancellationToken)
 {
     while (count > 0)
     {
         var backingBytes = buffer.AccessBackingBytes(offset);
         var bytesToRead = Math.Min(count, backingBytes.Count);
         var bytesRead = await stream.ReadAsync(backingBytes.Array, backingBytes.Offset, bytesToRead, cancellationToken);
         if (bytesRead == 0)
         {
             throw new EndOfStreamException();
         }
         offset += bytesRead;
         count -= bytesRead;
     }
 }
		public void OnElement(IByteSource source, DicomTag tag, DicomVR vr, IByteBuffer data) {
			DicomElement element;
			switch (vr.Code) {
				case "AE": element = new DicomApplicationEntity(tag, data); break;
				case "AS": element = new DicomAgeString(tag, data); break;
				case "AT": element = new DicomAttributeTag(tag, data); break;
				case "CS": element = new DicomCodeString(tag, data); break;
				case "DA": element = new DicomDate(tag, data); break;
				case "DS": element = new DicomDecimalString(tag, data); break;
				case "DT": element = new DicomDateTime(tag, data); break;
				case "FD": element = new DicomFloatingPointDouble(tag, data); break;
				case "FL": element = new DicomFloatingPointSingle(tag, data); break;
				case "IS": element = new DicomIntegerString(tag, data); break;
				case "LO": element = new DicomLongString(tag, _encodings.Peek(), data); break;
				case "LT": element = new DicomLongText(tag, _encodings.Peek(), data); break;
				case "OB": element = new DicomOtherByte(tag, data); break;
				case "OD": element = new DicomOtherDouble(tag, data); break;
				case "OF": element = new DicomOtherFloat(tag, data); break;
				case "OW": element = new DicomOtherWord(tag, data); break;
				case "PN": element = new DicomPersonName(tag, _encodings.Peek(), data); break;
				case "SH": element = new DicomShortString(tag, _encodings.Peek(), data); break;
				case "SL": element = new DicomSignedLong(tag, data); break;
				case "SS": element = new DicomSignedShort(tag, data); break;
				case "ST": element = new DicomShortText(tag, _encodings.Peek(), data); break;
				case "TM": element = new DicomTime(tag, data); break;
				case "UC": element = new DicomUnlimitedCharacters(tag, _encodings.Peek(), data); break;
				case "UI": element = new DicomUniqueIdentifier(tag, data); break;
				case "UL": element = new DicomUnsignedLong(tag, data); break;
				case "UN": element = new DicomUnknown(tag, data); break;
				case "UR": element = new DicomUniversalResource(tag, _encodings.Peek(), data); break;
				case "US": element = new DicomUnsignedShort(tag, data); break;
				case "UT": element = new DicomUnlimitedText(tag, _encodings.Peek(), data); break;
				default:
					throw new DicomDataException("Unhandled VR in DICOM parser observer: {0}", vr.Code);
			}

			if (element.Tag == DicomTag.SpecificCharacterSet) {
				Encoding encoding = _encodings.Peek();
				if (element.Count > 0)
					encoding = DicomEncoding.GetEncoding(element.Get<string>(0));
				_encodings.Pop();
				_encodings.Push(encoding);
			}

			DicomDataset ds = _datasets.Peek();
			ds.Add(element);
		}
Example #30
0
 public void processMessage(IByteBuffer data)
 {
     if (data.available() <= 0)
     {
         return;
     }
     int id = data.readByte();
     if (id == 0)
     {
         onBlock(data);
     }
     else
     {
         data.setReadPos(data.getReadPos() - 1);
         //messageArrived(data);
     }
 }
Example #31
0
 public void Serialize(IByteBuffer byteBuffer, GetBlockHeadersMessage message)
 {
     byte[] oldWay = Serialize(message);
     byteBuffer.EnsureWritable(oldWay.Length, true);
     byteBuffer.WriteBytes(oldWay);
 }
        protected internal override void Encode(IChannelHandlerContext context, WebSocketFrame message, List <object> output)
        {
            if (message is TextWebSocketFrame)
            {
                // Text frame
                IByteBuffer data = message.Content;

                output.Add(_0X00.Duplicate());
                output.Add(data.Retain());
                output.Add(_0XFF.Duplicate());
            }
            else if (message is CloseWebSocketFrame)
            {
                // Close frame, needs to call duplicate to allow multiple writes.
                // See https://github.com/netty/netty/issues/2768
                output.Add(_0XFF_0X00.Duplicate());
            }
            else
            {
                // Binary frame
                IByteBuffer data    = message.Content;
                int         dataLen = data.ReadableBytes;

                IByteBuffer buf     = context.Allocator.Buffer(5);
                bool        release = true;
                try
                {
                    // Encode type.
                    buf.WriteByte(0x80);

                    // Encode length.
                    int b1 = dataLen.RightUShift(28) & 0x7F;
                    int b2 = dataLen.RightUShift(14) & 0x7F;
                    int b3 = dataLen.RightUShift(7) & 0x7F;
                    int b4 = dataLen & 0x7F;
                    if (b1 == 0)
                    {
                        if (b2 == 0)
                        {
                            if (b3 == 0)
                            {
                                buf.WriteByte(b4);
                            }
                            else
                            {
                                buf.WriteByte(b3 | 0x80);
                                buf.WriteByte(b4);
                            }
                        }
                        else
                        {
                            buf.WriteByte(b2 | 0x80);
                            buf.WriteByte(b3 | 0x80);
                            buf.WriteByte(b4);
                        }
                    }
                    else
                    {
                        buf.WriteByte(b1 | 0x80);
                        buf.WriteByte(b2 | 0x80);
                        buf.WriteByte(b3 | 0x80);
                        buf.WriteByte(b4);
                    }

                    // Encode binary data.
                    output.Add(buf);
                    output.Add(data.Retain());
                    release = false;
                }
                finally
                {
                    if (release)
                    {
                        buf.Release();
                    }
                }
            }
        }
Example #33
0
        public GetBlockHeadersMessage Deserialize(IByteBuffer byteBuffer)
        {
            NettyRlpStream rlpStream = new NettyRlpStream(byteBuffer);

            return(Deserialize(rlpStream));
        }
Example #34
0
 public void Encode(IByteBuffer packet)
 {
     packet.WriteVInt(ClientTick);
 }
Example #35
0
 public static IByteBuffer WriteStruct(this IByteBuffer @this, IByteBuffer data, int length)
 {
     @this.WriteScalar(length)
     .WriteBytes(data, length);
     return(@this);
 }
Example #36
0
 public static IByteBuffer WriteStruct(this IByteBuffer @this, IByteBuffer data)
 {
     @this.WriteScalar(data.ReadableBytes)
     .WriteBytes(data);
     return(@this);
 }
        protected DefaultByteBufferHolder(IByteBuffer buffer)
        {
            Contract.Requires(buffer != null);

            this.buffer = buffer;
        }
Example #38
0
 public Http2HeaderBlockIOTest()
 {
     this.encoder = new DefaultHttp2HeadersEncoder();
     this.decoder = new DefaultHttp2HeadersDecoder(false);
     this.buffer  = Unpooled.Buffer();
 }
Example #39
0
 public RespondToAllianceJoinRequestMessage(Device device, IByteBuffer buffer) : base(device, buffer)
 {
     Id = 14321;
 }
Example #40
0
 public static IByteBuffer WriteStruct(this IByteBuffer @this, byte[] data)
 {
     @this.WriteScalar(data.Length)
     .WriteBytes(data);
     return(@this);
 }
 public JoinAllianceMessage(Device device, IByteBuffer buffer) : base(device, buffer)
 {
     Id = 14305;
 }
Example #42
0
 /// <summary>
 /// Write bytes form the given {@link ByteBuf} to the underlying {@link java.nio.channels.Channel}.
 /// @param buf           the {@link ByteBuf} from which the bytes should be written
 /// @return amount       the amount of written bytes
 /// </summary>
 protected abstract int DoWriteBytes(IByteBuffer buf);
Example #43
0
            public override void FinishRead(SocketChannelAsyncOperation operation)
            {
                AbstractSocketByteChannel ch = this.Channel;

                ch.ResetState(StateFlags.ReadScheduled);
                IChannelConfiguration config = ch.Configuration;

                if (!config.AutoRead && !ch.ReadPending)
                {
                    // ChannelConfig.setAutoRead(false) was called in the meantime
                    //removeReadOp(); -- noop with IOCP, just don't schedule receive again
                    return;
                }

                IChannelPipeline     pipeline           = ch.Pipeline;
                IByteBufferAllocator allocator          = config.Allocator;
                int maxMessagesPerRead                  = config.MaxMessagesPerRead;
                IRecvByteBufAllocatorHandle allocHandle = this.RecvBufAllocHandle;

                IByteBuffer byteBuf  = null;
                int         messages = 0;
                bool        close    = false;

                try
                {
                    operation.Validate();

                    int  totalReadAmount  = 0;
                    bool readPendingReset = false;
                    do
                    {
                        byteBuf = allocHandle.Allocate(allocator);
                        int writable        = byteBuf.WritableBytes;
                        int localReadAmount = ch.DoReadBytes(byteBuf);
                        if (localReadAmount <= 0)
                        {
                            // not was read release the buffer
                            byteBuf.Release();
                            byteBuf = null;
                            close   = localReadAmount < 0;
                            break;
                        }
                        if (!readPendingReset)
                        {
                            readPendingReset = true;
                            ch.ReadPending   = false;
                        }
                        pipeline.FireChannelRead(byteBuf);
                        byteBuf = null;

                        if (totalReadAmount >= int.MaxValue - localReadAmount)
                        {
                            // Avoid overflow.
                            totalReadAmount = int.MaxValue;
                            break;
                        }

                        totalReadAmount += localReadAmount;

                        // stop reading
                        if (!config.AutoRead)
                        {
                            break;
                        }

                        if (localReadAmount < writable)
                        {
                            // Read less than what the buffer can hold,
                            // which might mean we drained the recv buffer completely.
                            break;
                        }
                    }while (++messages < maxMessagesPerRead);

                    pipeline.FireChannelReadComplete();
                    allocHandle.Record(totalReadAmount);

                    if (close)
                    {
                        this.CloseOnRead();
                        close = false;
                    }
                }
                catch (Exception t)
                {
                    this.HandleReadException(pipeline, byteBuf, t, close);
                }
                finally
                {
                    // Check if there is a readPending which was not processed yet.
                    // This could be for two reasons:
                    // /// The user called Channel.read() or ChannelHandlerContext.read() input channelRead(...) method
                    // /// The user called Channel.read() or ChannelHandlerContext.read() input channelReadComplete(...) method
                    //
                    // See https://github.com/netty/netty/issues/2254
                    if (!close && (config.AutoRead || ch.ReadPending))
                    {
                        ch.DoBeginRead();
                    }
                }
            }
Example #44
0
 public IMessage CreateMessage(string address, IByteBuffer payload) => throw new InvalidOperationException("Must not receive messages from a client.");
Example #45
0
        async void Receive()
        {
            Message     message        = null;
            IByteBuffer messagePayload = null;

            try
            {
                while (true)
                {
                    message = await this.bridge.DeviceClient.ReceiveAsync(this.lifetimeCancellation.Token);

                    if (message == null)
                    {
                        this.messagingChannel.Close(null);
                        return;
                    }

                    PerformanceCounters.TotalCommandsReceived.Increment();
                    PerformanceCounters.CommandsReceivedPerSecond.Increment();

                    if (this.bridge.Settings.MaxOutboundRetransmissionEnforced && message.DeliveryCount > this.bridge.Settings.MaxOutboundRetransmissionCount)
                    {
                        CommonEventSource.Log.Info("Rejected message: high delivery count: " + message.DeliveryCount, null, this.bridge.DeviceId);
                        await this.RejectAsync(message.LockToken);

                        message.Dispose();
                        message = null;
                        continue;
                    }

                    using (Stream payloadStream = message.GetBodyStream())
                    {
                        long streamLength = payloadStream.Length;
                        if (streamLength > int.MaxValue)
                        {
                            throw new InvalidOperationException($"Message size ({streamLength.ToString()} bytes) is too big to process.");
                        }

                        int length = (int)streamLength;
                        messagePayload = this.allocator.Buffer(length, length);
                        await messagePayload.WriteBytesAsync(payloadStream, length);

                        Contract.Assert(messagePayload.ReadableBytes == length);
                    }

                    var msg = new IotHubClientMessage(message, messagePayload);
                    msg.Properties[TemplateParameters.DeviceIdTemplateParam] = this.bridge.DeviceId;
                    string address;
                    if (!this.addressFormatter(msg, out address))
                    {
                        CommonEventSource.Log.Info("Rejected message: could not format topic", null, this.bridge.DeviceId);
                        messagePayload.Release();
                        await this.RejectAsync(message.LockToken); // todo: fork await

                        message.Dispose();
                        message        = null;
                        messagePayload = null;
                        continue;
                    }
                    msg.Address = address;

                    this.messagingChannel.Handle(msg, this);

                    message        = null; // ownership has been transferred to messagingChannel
                    messagePayload = null;
                }
            }
            catch (IotHubException ex)
            {
                this.messagingChannel.Close(ex.ToMessagingException());
            }
            catch (Exception ex)
            {
                this.messagingChannel.Close(ex);
            }
            finally
            {
                message?.Dispose();
                if (messagePayload != null)
                {
                    ReferenceCountUtil.SafeRelease(messagePayload);
                }
            }
        }
 public void OnFragmentSequenceItem(IByteSource source, IByteBuffer data)
 {
     _fragment.Add(data);
 }
        protected override async void DoBeginRead()
        {
            IByteBuffer byteBuffer = null;
            IRecvByteBufAllocatorHandle allocHandle = null;
            bool close = false;

            try
            {
                if (!this.Open || this.ReadPending)
                {
                    return;
                }

                this.ReadPending = true;
                IByteBufferAllocator allocator = this.Configuration.Allocator;
                allocHandle = this.Configuration.RecvByteBufAllocator.NewHandle();
                allocHandle.Reset(this.Configuration);
                do
                {
                    byteBuffer = allocHandle.Allocate(allocator);
                    allocHandle.LastBytesRead = await this.DoReadBytes(byteBuffer);

                    if (allocHandle.LastBytesRead <= 0)
                    {
                        // nothing was read -> release the buffer.
                        byteBuffer.Release();
                        byteBuffer = null;
                        close      = allocHandle.LastBytesRead < 0;
                        break;
                    }

                    this.Pipeline.FireChannelRead(byteBuffer);
                    allocHandle.IncMessagesRead(1);
                }while (allocHandle.ContinueReading());

                allocHandle.ReadComplete();
                this.ReadPending = false;
                this.Pipeline.FireChannelReadComplete();
            }
            catch (Exception e) when(!e.IsFatal())
            {
                Events.ReadException(this.correlationId, e);

                // Since this method returns void, all exceptions must be handled here.
                byteBuffer.SafeRelease();
                allocHandle?.ReadComplete();
                this.ReadPending = false;

                // WebSocket should change its state when an exception is thrown,
                // but it doesn't (see https://github.com/dotnet/corefx/issues/26219)
                // so we'll abort the connection here.
                this.Abort();

                this.Pipeline.FireChannelReadComplete();
                this.Pipeline.FireExceptionCaught(e);
                close = true;
            }

            if (close)
            {
                if (this.Active)
                {
                    await this.HandleCloseAsync();
                }
            }
        }
        public void SimpleSend(IByteBuffer source, bool bindClient, IByteBufferAllocator allocator, AddressFamily addressFamily, byte[] expectedData, int count)
        {
            SocketDatagramChannel serverChannel = null;
            IChannel clientChannel = null;
            var      serverGroup   = new MultithreadEventLoopGroup(1);
            var      clientGroup   = new MultithreadEventLoopGroup(1);

            try
            {
                var handler         = new TestHandler(expectedData);
                var serverBootstrap = new Bootstrap();
                serverBootstrap
                .Group(serverGroup)
                .ChannelFactory(() => new SocketDatagramChannel(addressFamily))
                .Option(ChannelOption.Allocator, allocator)
                .Option(ChannelOption.SoBroadcast, true)
                .Option(ChannelOption.IpMulticastLoopDisabled, false)
                .Handler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    channel.Pipeline.AddLast(nameof(SocketDatagramChannelUnicastTest), handler);
                }));

                IPAddress address = NetUtil.GetLoopbackAddress(addressFamily);
                this.Output.WriteLine($"Unicast server binding to:({addressFamily}){address}");
                Task <IChannel> task = serverBootstrap.BindAsync(address, IPEndPoint.MinPort);

                Assert.True(task.Wait(TimeSpan.FromMilliseconds(DefaultTimeOutInMilliseconds * 5)),
                            $"Unicast server binding to:({addressFamily}){address} timed out!");

                serverChannel = (SocketDatagramChannel)task.Result;
                var endPoint = (IPEndPoint)serverChannel.LocalAddress;

                var clientBootstrap = new Bootstrap();
                clientBootstrap
                .Group(clientGroup)
                .ChannelFactory(() => new SocketDatagramChannel(addressFamily))
                .Option(ChannelOption.Allocator, allocator)
                .Option(ChannelOption.SoBroadcast, true)
                .Option(ChannelOption.IpMulticastLoopDisabled, false)
                .Handler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    channel.Pipeline.AddLast("Dummy", new NetUtil.DummyHandler());
                }));

                var clientEndPoint = new IPEndPoint(
                    addressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any,
                    IPEndPoint.MinPort);

                clientBootstrap
                .LocalAddress(clientEndPoint)
                .RemoteAddress(new IPEndPoint(address, endPoint.Port));

                if (bindClient)
                {
                    this.Output.WriteLine($"Unicast client binding to:({addressFamily}){address}");
                    task = clientBootstrap.BindAsync(clientEndPoint);

                    Assert.True(task.Wait(TimeSpan.FromMilliseconds(DefaultTimeOutInMilliseconds * 5)),
                                $"Unicast client binding to:({clientEndPoint}) timed out!");
                    clientChannel = task.Result;
                }
                else
                {
                    this.Output.WriteLine($"Register client binding to:({addressFamily}){address}");
                    task = (Task <IChannel>)clientBootstrap.RegisterAsync();
                    Assert.True(task.Wait(TimeSpan.FromMilliseconds(DefaultTimeOutInMilliseconds)), "Unicast client register timed out!");
                    clientChannel = task.Result;
                }

                for (int i = 0; i < count; i++)
                {
                    var packet = new DatagramPacket((IByteBuffer)source.Retain(), new IPEndPoint(address, endPoint.Port));
                    clientChannel.WriteAndFlushAsync(packet).Wait();
                    Assert.True(handler.WaitForResult());

                    var duplicatedPacket = (DatagramPacket)packet.Duplicate();
                    duplicatedPacket.Retain();
                    clientChannel.WriteAndFlushAsync(duplicatedPacket).Wait();
                    Assert.True(handler.WaitForResult());
                }
            }
            finally
            {
                serverChannel?.CloseAsync().Wait(TimeSpan.FromMilliseconds(DefaultTimeOutInMilliseconds));
                clientChannel?.CloseAsync().Wait(TimeSpan.FromMilliseconds(DefaultTimeOutInMilliseconds));

                source.Release();
                Task.WaitAll(
                    serverGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                    clientGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
            }
        }
 /// <summary>
 /// Rent a buffer -> return it -> re-rent -> verify if it's array points to the previous location
 /// </summary>
 private bool CheckIsRentingPooledBuffer <T>(int length)
     where T : struct
 {
     IByteBuffer buffer = this.manager.Allocate(length);
     ref byte    ptrToPreviousPosition0 = ref MemoryMarshal.GetReference <byte>(buffer.Array);
Example #50
0
 public static IByteBuffer WriteStruct(this IByteBuffer @this, byte[] data, int offset, int length)
 {
     @this.WriteScalar(length)
     .WriteBytes(data, offset, length);
     return(@this);
 }
Example #51
0
 public virtual void Decode(IByteBuffer buffer)
 {
 }
Example #52
0
        protected override void Encode(IChannelHandlerContext context, IPacket message, IByteBuffer output)
        {
            var socket = context.Channel.GetAttribute(NettyAttributes.SocketKey).Get();
            var dataLen = (short)message.Buffer.Length;
            var buffer = message.Buffer.ToArray();

            if (socket != null)
            {
                var seqSend = socket.SeqSend;
                var rawSeq = (short)((seqSend >> 16) ^ -(_transport.Version + 1));

                if (socket.EncryptData)
                {
                    dataLen ^= rawSeq;

                    ShandaCipher.EncryptTransform(buffer);
                    _aesCipher.Transform(buffer, seqSend);
                }

                output.WriteShortLE(rawSeq);
                output.WriteShortLE(dataLen);
                output.WriteBytes(buffer);

                socket.SeqSend = _igCipher.Hash(seqSend, 4, 0);
            }
            else
            {
                output.WriteShortLE(dataLen);
                output.WriteBytes(buffer);
            }
        }
        public void OnElement(IByteSource source, DicomTag tag, DicomVR vr, IByteBuffer data)
        {
            DicomElement element;

            switch (vr.Code)
            {
            case "AE":
                element = new DicomApplicationEntity(tag, data);
                break;

            case "AS":
                element = new DicomAgeString(tag, data);
                break;

            case "AT":
                element = new DicomAttributeTag(tag, data);
                break;

            case "CS":
                element = new DicomCodeString(tag, data);
                break;

            case "DA":
                element = new DicomDate(tag, data);
                break;

            case "DS":
                element = new DicomDecimalString(tag, data);
                break;

            case "DT":
                element = new DicomDateTime(tag, data);
                break;

            case "FD":
                element = new DicomFloatingPointDouble(tag, data);
                break;

            case "FL":
                element = new DicomFloatingPointSingle(tag, data);
                break;

            case "IS":
                element = new DicomIntegerString(tag, data);
                break;

            case "LO":
                element = new DicomLongString(tag, _encodings.Peek(), data);
                break;

            case "LT":
                element = new DicomLongText(tag, _encodings.Peek(), data);
                break;

            case "OB":
                element = new DicomOtherByte(tag, data);
                break;

            case "OD":
                element = new DicomOtherDouble(tag, data);
                break;

            case "OF":
                element = new DicomOtherFloat(tag, data);
                break;

            case "OW":
                element = new DicomOtherWord(tag, data);
                break;

            case "PN":
                element = new DicomPersonName(tag, _encodings.Peek(), data);
                break;

            case "SH":
                element = new DicomShortString(tag, _encodings.Peek(), data);
                break;

            case "SL":
                element = new DicomSignedLong(tag, data);
                break;

            case "SS":
                element = new DicomSignedShort(tag, data);
                break;

            case "ST":
                element = new DicomShortText(tag, _encodings.Peek(), data);
                break;

            case "TM":
                element = new DicomTime(tag, data);
                break;

            case "UC":
                element = new DicomUnlimitedCharacters(tag, _encodings.Peek(), data);
                break;

            case "UI":
                element = new DicomUniqueIdentifier(tag, data);
                break;

            case "UL":
                element = new DicomUnsignedLong(tag, data);
                break;

            case "UN":
                element = new DicomUnknown(tag, data);
                break;

            case "UR":
                element = new DicomUniversalResource(tag, _encodings.Peek(), data);
                break;

            case "US":
                element = new DicomUnsignedShort(tag, data);
                break;

            case "UT":
                element = new DicomUnlimitedText(tag, _encodings.Peek(), data);
                break;

            default:
                throw new DicomDataException("Unhandled VR in DICOM parser observer: {0}", vr.Code);
            }

            if (element.Tag == DicomTag.SpecificCharacterSet)
            {
                Encoding encoding = _encodings.Peek();
                if (element.Count > 0)
                {
                    encoding = DicomEncoding.GetEncoding(element.Get <string>(0));
                }
                _encodings.Pop();
                _encodings.Push(encoding);
            }

            DicomDataset ds = _datasets.Peek();

            ds.Add(element);
        }
 protected override void DecodeLast(IChannelHandlerContext context, IByteBuffer input, List <object> output)
 {
     base.DecodeLast(context, input, output);
 }
Example #55
0
 public virtual void Encode(IByteBuffer buffer) => FixedHeader.WriteTo(buffer);
Example #56
0
        public static IByteBuffer ReadStruct(this IByteBuffer @this)
        {
            var length = @this.ReadScalar();

            return(@this.ReadSlice(length));
        }
Example #57
0
        // todo: support FileRegion
        ///// <summary>
        // /// Write a {@link FileRegion}
        // *
        // /// @param region        the {@link FileRegion} from which the bytes should be written
        // /// @return amount       the amount of written bytes
        // /// </summary>
        //protected abstract long doWriteFileRegion(FileRegion region);

        /// <summary>
        /// Read bytes into the given {@link ByteBuf} and return the amount.
        /// </summary>
        protected abstract int DoReadBytes(IByteBuffer buf);
        public static string ReadLongString(this IByteBuffer buffer, Encoding encoding)
        {
            int length = buffer.ReadInt();

            return(length <= 0 ? string.Empty : buffer.ReadString(length, encoding));
        }
Example #59
0
 public static IByteBuffer Decode(IByteBuffer src) => Decode(src, Base64Dialect.Standard);
Example #60
0
 public GoHomeMessage(Device device, IByteBuffer buffer) : base(device, buffer)
 {
     Id            = 14101;
     Save          = true;
     RequiredState = Device.State.Battle;
 }