示例#1
0
        internal async Task ListenToNetworkStreamAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    if (!await ReadFixedAmountAsync(_sizeBuffer, 0, 4, cancellationToken))
                    {
                        return;
                    }

                    int size   = BinaryReaderExt.ToInt32LittleEndian(_sizeBuffer);
                    var packet = new byte[size];

                    if (!await ReadFixedAmountAsync(packet, 0, size, cancellationToken))
                    {
                        return;
                    }

                    ParsePacket(size, packet);
                }
                catch (TimeoutException) { }
                catch (ObjectDisposedException)
                {
                    OnConnectionStateChange?.Invoke(ConnectionStateChange.ConnectionLost);
                    Disconnect();
                    return;
                }
                catch (IOException)
                {
                    OnConnectionStateChange?.Invoke(ConnectionStateChange.ConnectionLost);
                    Disconnect();
                    return;
                }
                catch (Exception e)
                {
                    Log(e.ToString());
                    return;
                }
            }
        }