コード例 #1
0
        /// <summary>
        /// The callback of the read async method.
        /// </summary>
        /// <param name="result">The result.</param>
        private void EndRead(IAsyncResult result)
        {
            int length = _stream.EndRead(result);

            // asyncState is the buffer used in the ctor call which does the first read.
            byte[] asyncState = (byte[])result.AsyncState;
            if (length > 0)
            {
                byte[] destinationArray = new byte[length];
                Array.Copy(asyncState, 0, destinationArray, 0, length);
                OnMessageReceived(new ContainerEventArgs <byte[]>(destinationArray));
            }

            lock (_instanceLock)
            {
                if (_stream.IsConnected)
                {
                    _stream.BeginRead(asyncState, 0, ConstantsEnums.BufferLength, new AsyncCallback(EndRead), asyncState);
                }
                else
                {
                    this.Disconnected.RaiseEvent(this);
                }
            }
        }
コード例 #2
0
ファイル: PipeProxy.cs プロジェクト: yonglehou/Symbiote
        public void ReadAsync(PipeStream stream, int timeout, Action <byte[]> onComplete)
        {
            var memoryStream = new MemoryStream();
            var buffer       = new byte[8 * 1024];
            var read         = 0;

            if (stream.CanTimeout)
            {
                stream.ReadTimeout = timeout;
            }

            Future.Of(
                x => stream.BeginRead(buffer, 0, buffer.Length, x, null),
                x =>
            {
                read = stream.EndRead(x);
                if (read > 0)
                {
                    memoryStream.Write(buffer, 0, read);
                }

                if (stream.IsMessageComplete && memoryStream.Length > 0)
                {
                    onComplete(memoryStream.ToArray());
                    memoryStream.Close();
                    memoryStream.Dispose();
                    memoryStream = new MemoryStream();
                }
                return(read);
            })
            .LoopWhile(() => Running)
            .Start();
        }
コード例 #3
0
        private void OnRead(IAsyncResult ar)
        {
            int n = stream.EndRead(ar);

            if (n > 0)
            {
                Console.WriteLine("Client.Read({0}): {1}", id, Encoding.ASCII.GetString(header, 0, n));

                stream.BeginRead(header, 0, header.Length, OnRead, this);
            }
        }
コード例 #4
0
    public static Task <int> ReadPipeAsync(this PipeStream pipe, byte[] buffer, int offset, int count, CancellationToken cancellationToken)
    {
        if (cancellationToken.IsCancellationRequested)
        {
            return(Task.FromCanceled <int>(cancellationToken));
        }
        var registration = cancellationToken.Register(() => CancelPipeIo(pipe));
        var async        = pipe.BeginRead(buffer, offset, count, null, null);

        return(new Task <int>(() => {
            try { return pipe.EndRead(async); }
            finally { registration.Dispose(); }
        }, cancellationToken));
    }
コード例 #5
0
        private void EndRead(IAsyncResult result)
        {
            int length     = _Stream.EndRead(result);
            var asyncState = (byte[])result.AsyncState;

            if (length > 0)
            {
                var destinationArray = new byte[length];
                Array.Copy(asyncState, 0, destinationArray, 0, length);
                OnMessageReceived(new MessageEventArgs(destinationArray));
            }
            lock (_InstanceLock)
            {
                _Stream.BeginRead(asyncState, 0, BUFFER_LENGTH, EndRead, asyncState);
            }
        }
コード例 #6
0
        private void EndRead(IAsyncResult result)
        {
            int length = mStream.EndRead(result);

            byte[] asyncState = (byte[])result.AsyncState;
            if (length > 0)
            {
                byte[] destinationArray = new byte[length];
                Array.Copy(asyncState, 0, destinationArray, 0, length);
                OnMessageReceived(new MessageEventArgs(destinationArray));
            }
            lock (mNamedPipeLock)
            {
                mStream.BeginRead(asyncState, 0, kMaxBufferSize, new AsyncCallback(EndRead), asyncState);
            }
        }
コード例 #7
0
        private void BeginRead(ManualResetEventSlim manualEvent, Action <byte[]> callback)
        {
            var buffer = new byte[PackageSize];

            PipeStream.BeginRead(buffer, 0, buffer.Length, (result) =>
            {
                var bytesRead = PipeStream.EndRead(result);

                if (bytesRead > 0)
                {
                    callback(buffer.Take(bytesRead).ToArray());
                }
                else
                {
                    Close();
                }

                manualEvent.Set();
            }, null);
        }
コード例 #8
0
        protected override int Read(byte[] buffer, int offset, int count)
        {
            pipe = (PipeStream)Stream;
            AsyncCallback cb = delegate(IAsyncResult ar)
            {
                //wHandle = ar.AsyncWaitHandle;

                pipe.EndRead(ar);
                ((ManualResetEvent)wHandle).Set();
            };

            //((AutoResetEvent)wHandle).
            IAsyncResult iar = pipe.BeginRead(buffer, offset, count, cb, wHandle);


            Thread.Sleep(100);
            wHandle.WaitOne();
            ((ManualResetEvent)wHandle).Reset();

            return(count);
        }
コード例 #9
0
        private void EndReading(IAsyncResult ar)
        {
            try
            {
                if (State == ResonanceComponentState.Connected)
                {
                    _pipeStream.EndRead(ar);

                    int expectedSize = BitConverter.ToInt32(_size_buffer, 0);

                    if (expectedSize > 0)
                    {
                        byte[] data = new byte[expectedSize];
                        int    read = 0;

                        while (read < expectedSize)
                        {
                            read += _pipeStream.Read(data, read, expectedSize - read);

                            if (State != ResonanceComponentState.Connected)
                            {
                                break;
                            }
                        }

                        OnDataAvailable(data);
                    }
                    else
                    {
                        Thread.Sleep(2000);
                    }

                    WaitForData();
                }
            }
            catch (Exception ex)
            {
                OnFailed(ex, "Error occurred while trying to read from the pipe stream.");
            }
        }
コード例 #10
0
 private void EndRead(IAsyncResult result)
 {
     // this can throw an exception when it first starts up, so...
     try
     {
         int length     = _Stream.EndRead(result);
         var asyncState = (byte[])result.AsyncState;
         if (length > 0)
         {
             var destinationArray = new byte[length];
             Array.Copy(asyncState, 0, destinationArray, 0, length);
             OnMessageReceived(new MessageEventArgs(destinationArray));
         }
         lock (_InstanceLock)
         {
             _Stream.BeginRead(asyncState, 0, BUFFER_LENGTH,
                               EndRead, asyncState);
         }
     }
     catch
     {
     }
 }
コード例 #11
0
        public int Read(byte[] buffer, int offset, int length, int timeoutMs)
        {
            if (!WaitForConnection(timeoutMs))
            {
                return(-BacnetMstpProtocolTransport.ETIMEDOUT);
            }

            if (_currentRead == null)
            {
                try
                {
                    _currentRead = _conn.BeginRead(buffer, offset, length, null, null);
                }
                catch (Exception)
                {
                    Disconnect();
                    return(-1);
                }
            }

            if (!_currentRead.IsCompleted && !_currentRead.AsyncWaitHandle.WaitOne(timeoutMs))
            {
                return(-BacnetMstpProtocolTransport.ETIMEDOUT);
            }

            try
            {
                var rx = _conn.EndRead(_currentRead);
                _currentRead = null;
                return(rx);
            }
            catch (Exception)
            {
                Disconnect();
                return(-1);
            }
        }
コード例 #12
0
        private void WhenReceived(IAsyncResult ar)
        {
            try
            {
                var read = _pipeStream.EndRead(ar);
                if (read == 0)
                {
                    Log($"Nothing to read, connection closed.");
                    return;
                }

                _cursor += read;
                Log($"Received {read} bytes.");
                Begin(_cursor == _buffer.Length);
            }
            catch (NullReferenceException)
            {
                Log($"Nothing to read, connection closed.");
            }
            catch (IOException e)
            {
                Log($"End Read error: {e}.");
            }
        }
コード例 #13
0
ファイル: IPCBase.cs プロジェクト: egshels/Sources
        public virtual void ReadCallback(IAsyncResult result)
        {
            WeGameHelper.WriteDebugString("ReadCallback: " + Thread.CurrentThread.ManagedThreadId.ToString());
            IPCContent iPCContent = (IPCContent)result.AsyncState;

            try
            {
                int num = _pipeStream.EndRead(result);
                if (!iPCContent.CancelToken.IsCancellationRequested)
                {
                    if (num > 0)
                    {
                        _totalData.AddRange(iPCContent.data.Take(num));
                        if (_pipeStream.IsMessageComplete)
                        {
                            AddPackToList(_totalData);
                            _totalData = new List <byte>();
                        }
                    }
                }
                else
                {
                    WeGameHelper.WriteDebugString("IPCBase.ReadCallback.cancel");
                }
            }
            catch (IOException ex)
            {
                _pipeBrokenFlag = true;
                WeGameHelper.WriteDebugString("ReadCallback Exception, {0}", ex.Message);
            }
            catch (InvalidOperationException ex2)
            {
                _pipeBrokenFlag = true;
                WeGameHelper.WriteDebugString("ReadCallback Exception, {0}", ex2.Message);
            }
        }
コード例 #14
0
 public override int EndRead(IAsyncResult asyncResult) => _underlying.EndRead(asyncResult);
コード例 #15
0
        void HandleRead(IAsyncResult ar)
        {
            lock (comlock)
            {
                int bytes;
                try
                {
                    bytes = Pipe.EndRead(ar);
                    if (bytes == 0)
                    {
                        Debug.Print(ar.ToString());
                        Debug.Print(ar.CompletedSynchronously.ToString());
                        Debug.Print(ar.IsCompleted.ToString());
                        onFailure("No bytes to read, pipe closed");
                        return;
                    }
                }
                catch (Exception e)
                {
                    Debug.Print(string.Format("End Read Failed {0}", e.ToString()));
                    onFailure("End read threw exception " + e.ToString());
                    return;
                }

                try
                {
                    processData(bytes);

                    try {
                        Pipe.BeginRead(buffer, bufferreadpos, buffersize - bufferreadpos, HandleRead, this);
                    }
                    catch {
                        onFailure("Pipe broken");
                        return;
                    }
                }
                catch (EndOfStreamException)
                {
                    if (bufferreadpos == buffersize)
                    {
                        buffersize = buffersize * 2;
                        byte[] newbuffer = new byte[buffersize];
                        buffer.CopyTo(newbuffer, 0);
                        buffer = newbuffer;
                    }
                    try
                    {
                        Debug.Print("new read " + bufferreadpos.ToString() + " " + (buffersize - bufferreadpos).ToString());
                        if (!Pipe.CanRead)
                        {
                            Debug.Print("For some reason I can't read from this pipe.  Ideas?");
                        }
                        if (!Pipe.IsConnected)
                        {
                            onFailure("Pipe has gone away");
                            return;
                        }
                        try {
                            Pipe.BeginRead(buffer, bufferreadpos, buffersize - bufferreadpos, HandleRead, this);
                        }
                        catch {
                            onFailure("Pipe broken");
                            return;
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.Print("Communicator found too little to read : " + buffersize.ToString() + " " + bufferreadpos.ToString() + " " + e.ToString());
                        onFailure("Insufficient data to read");
                        return;
                    }
                }
                catch (Exception e)
                {
                    Debug.Print("Communicator failure :" + e.ToString());
                    onFailure("Handle read comms failure : " + e.ToString());
                    return;
                }
            }
        }