예제 #1
0
파일: IPCBase.cs 프로젝트: egshels/Sources
        protected virtual bool BeginReadData()
        {
            bool       result     = false;
            IPCContent iPCContent = new IPCContent
            {
                data        = new byte[BufferSize],
                CancelToken = _cancelTokenSrc.Token
            };

            WeGameHelper.WriteDebugString("BeginReadData");
            try
            {
                if (_pipeStream == null)
                {
                    return(result);
                }
                _pipeStream.BeginRead(iPCContent.data, 0, BufferSize, ReadCallback, iPCContent);
                result = true;
                return(result);
            }
            catch (IOException ex)
            {
                _pipeBrokenFlag = true;
                WeGameHelper.WriteDebugString("BeginReadData Exception, {0}", ex.Message);
                return(result);
            }
        }
예제 #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NamedPipeStreamConnection"/> class.
 /// </summary>
 /// <param name="stream">The stream.</param>
 /// <param name="pipeName">The name of the named pipe used</param>
 public NamedPipeStreamConnection(PipeStream stream, string pipeName) : base(pipeName)
 {
     _instanceLock = new object();
     _stream       = stream;
     byte[] buffer = new byte[ConstantsEnums.BufferLength];
     _stream.BeginRead(buffer, 0, ConstantsEnums.BufferLength, new AsyncCallback(this.EndRead), buffer);
 }
예제 #3
0
 public NamedPipeTransport(PipeStream stream, string name) : base(name)
 {
     mNamedPipeLock = new object();
     mStream        = stream;
     byte[] buffer = new byte[kMaxBufferSize];
     mStream.BeginRead(buffer, 0, kMaxBufferSize, new AsyncCallback(EndRead), buffer);
 }
예제 #4
0
        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();
        }
예제 #5
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);
                }
            }
        }
        public NamedPipeStreamConnection(PipeStream stream, string pipeName) : base(pipeName)
        {
            _InstanceLock = new object();
            _Stream       = stream;
            var buffer = new byte[BUFFER_LENGTH];

            _Stream.BeginRead(buffer, 0, BUFFER_LENGTH, EndRead, buffer);
        }
예제 #7
0
        public Client(string serverName, string name)
        {
            IpcClientPipe clientPipe = new IpcClientPipe(serverName, name);

            stream = clientPipe.Connect(1000);

            stream.BeginRead(header, 0, header.Length, OnRead, this);
        }
예제 #8
0
        /// <summary>
        /// Extends BeginRead so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// pipestream.BeginRead(buffer, offset, count, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginRead(this PipeStream pipestream, Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback)
        {
            if (pipestream == null)
            {
                throw new ArgumentNullException("pipestream");
            }

            return(pipestream.BeginRead(buffer, offset, count, callback, null));
        }
예제 #9
0
 public void SetupReader()
 {
     this.bufferreadpos = 0;
     this.bufferstartreadpos = 0;
     buffersize = 1024;
     buffer = new byte[1024];
     if (!Pipe.IsConnected) {
         onFailure("Pipe is missing");
         return;
     }
     try {
         Pipe.BeginRead(this.buffer, 0, this.buffersize, HandleRead, this);
     }
     catch {
         onFailure("Pipe is missing on BeginRead");
         throw;
     }
 }
예제 #10
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);
            }
        }
예제 #11
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));
    }
예제 #12
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
     {
     }
 }
예제 #13
0
        /// <summary>
        /// Extends BeginRead so that buffer offset of 0 and call to Array.Length are not needed.
        /// <example>
        /// pipestream.BeginRead(buffer, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginRead(this PipeStream pipestream, Byte[] buffer, AsyncCallback callback)
        {
            if (pipestream == null)
            {
                throw new ArgumentNullException("pipestream");
            }

            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            return(pipestream.BeginRead(buffer, 0, buffer.Length, callback));
        }
예제 #14
0
 private void WaitForData()
 {
     try
     {
         if (State == ResonanceComponentState.Connected)
         {
             _size_buffer = new byte[4];
             _pipeStream.BeginRead(_size_buffer, 0, _size_buffer.Length, EndReading, null);
         }
     }
     catch (Exception ex)
     {
         OnFailed(ex, "Error occurred while trying to read from the pipe stream.");
     }
 }
예제 #15
0
        private void Begin(bool init)
        {
            if (init)
            {
                if (_buffer != null && !_processingHeader)
                {
                    string message = Encoding.Unicode.GetString(_buffer);
                    Log("Received message: [" + message + "] (" + _buffer.Length + " bytes).");

                    if (RaiseReceivedMessage != null)
                    {
                        RaiseReceivedMessage.Invoke(this, message);
                    }
                }
                _processingHeader = !_processingHeader;
                int len = _processingHeader ? 4 : BitConverter.ToInt32(_buffer, 0);
                if (len < 0)
                {
                    Log("Got invalid length, synchro lost. Aborting!");
                    _pipeStream.Close();
                    return;
                }
                _buffer = new byte[len];
                _cursor = 0;
                if (!_processingHeader && _buffer.Length == 0)
                {
                    // we have NO DATA to read, notify of empty message and wait to read again.
                    Log("Empty message.");
                    Begin(true);
                    return;
                }
            }

            try
            {
                int bufferLength = _buffer.Length - _cursor;
                _pipeStream.BeginRead(_buffer, _cursor, bufferLength, WhenReceived, null);
                Log("Waiting to read (" + bufferLength + " bytes).");
            }
            catch (ObjectDisposedException)
            {
                Log("Nothing to read, connection closed.");
            }
            catch (IOException e)
            {
                Log("Begin Read error:" + e);
            }
        }
        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);
            }
        }
예제 #17
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);
            }
        }
예제 #18
0
        private static bool PrimitiveReadData(byte[] buffer, PipeStream pipeStream, int millisecondsTimeout, CancellationToken?cancellationToken)
        {
            //读取响应数据长度
            IAsyncResult asyncResult = pipeStream.BeginRead(buffer, 0, buffer.Length, null, null);

            //var readDataLengthTask = pipeStream.ReadAsync(buffer, 0, buffer.Length);
            if (millisecondsTimeout >= Timeout.Infinite)
            {
                if (!asyncResult.AsyncWaitHandle.WaitOne(millisecondsTimeout))
                {
                    return(true);
                }
            }

            return(false);
        }
예제 #19
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);
        }
예제 #20
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);
        }
예제 #21
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);
            }
        }
예제 #22
0
 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => _underlying.BeginRead(buffer, offset, count, callback, state);