BeginRead() 개인적인 메소드

private BeginRead ( byte buffer, int offset, int count, AsyncCallback callback, Object state ) : IAsyncResult
buffer byte
offset int
count int
callback AsyncCallback
state Object
리턴 IAsyncResult
예제 #1
1
		private static Task<int> ReadTask(Stream stream, byte[] buffer, int offset, int count, object state)
		{
			var tcs = new TaskCompletionSource<int>();
			stream.BeginRead(buffer, offset, count, ar =>
			{
				try { tcs.SetResult(stream.EndRead(ar)); }
				catch (Exception exc) { tcs.SetException(exc); }
			}, state);
			return tcs.Task;
		}
예제 #2
1
 public static int ReadStream(Stream stream, byte[] buffer, int offset, int count, int timeout)
 {
     if (stream == null || buffer == null || buffer.Length < (offset + count))
         return -1;
     IAsyncResult arRead = stream.BeginRead(buffer, offset, count, null, null);
     if (!arRead.AsyncWaitHandle.WaitOne(timeout))
     {
         throw new TimeoutException("Could not read within the timeout period.");
     }
     return stream.EndRead(arRead);
 }
예제 #3
1
        public bool Connect()
        {
            try
            {
                //_socket.Connect(host, port);
                var connect_result = _socket.BeginConnect(host, port, null, null);
                if(!connect_result.AsyncWaitHandle.WaitOne(1500))
                {
                    throw new Exception();
                }
                _socket.EndConnect(connect_result);
            }
            catch
            {
                this.Destruct("Failed to connect.", true);
                return false;
            }
            _stream = _socket.GetStream();
            isConnected = true;
            Program._RconBox.SomethingToSend.Enabled = true;
            byte[] buff = new byte[1];
            AsyncCallback callback = null;
            callback = ar =>
            {
                try
                {
                    int bytes = _stream.EndRead(ar);

                    //Program._RconBox.OutputBox.Text += buff;
                    Program.wattosend.Add(buff[0]);
                    buff[0] = 0;

                    if (!this.isConnected || bytes == 0)
                    {
                        this.Destruct("Disconnected!");
                        return;
                    }

                    _stream.BeginRead(buff, 0, 1, callback, null);
                }
                catch
                {
                    this.Destruct("Reading has failed");
                }
            };
            _stream.BeginRead(buff, 0, 1, callback, null);
            this.Send("set redrawcmd false");
            this.Send("login " + this.pass);
            return true;
        }
        static IEnumerable<Task> CopyStream(Stream input, Stream output)
        {
            var buffer = new byte[0x2000];

            while (true)
            {
                // Create task to read from the input stream
                var read = Task<int>.Factory.FromAsync((buf, offset, count, callback, state) =>
                                                           {
                                                               Console.WriteLine("Issuing BeginRead");
                                                               return input.BeginRead(buf, offset, count, callback, state);
                                                           },
                                                           ar =>
                                                               {
                                                                   Console.WriteLine("Read completed");
                                                                   return input.EndRead(ar);
                                                               },
                                                               buffer, 0, buffer.Length, null);

                yield return read;

                // If we read no data, return
                if (read.Result == 0) break;

                // Create task to write to the output stream
                yield return Task.Factory.FromAsync((buf, offset, count, callback, state) =>
                                                           {
                                                               Console.WriteLine("Issuing BeginWrite");
                                                               return output.BeginWrite(buf, offset, count, callback, state);
                                                           },
                                                           ar =>
                                                               {
                                                                   Console.WriteLine("Write completed");
                                                                   output.EndWrite(ar);
                                                               }, buffer, 0, read.Result, null);
            }
        }
예제 #5
0
파일: BcpIO.cs 프로젝트: qifun/CSharpBcp
 private static void ReadUnsignedVarint(
     Stream stream,
     Bcp.ReadState readState,
     ProcessReadVarint processReadVarint,
     BcpDelegate.ExceptionHandler exceptionHandler)
 {
     var buffer = new byte[1];
     var i = 0;
     uint result = 0U;
     AsyncCallback asyncCallback = null;
     asyncCallback = asyncResult =>
     {
         try
         {
             int numBytesRead = stream.EndRead(asyncResult);
             if (numBytesRead != 1)
             {
                 exceptionHandler(new EndOfStreamException());
             }
             uint b = buffer[0];
             if (i < 32)
             {
                 if (b >= 0x80)
                 {
                     result |= ((b & 0x7f) << i);
                     i += 7;
                     stream.BeginRead(buffer, 0, 1, asyncCallback, readState);
                 }
                 else
                 {
                     result |= (b << i);
                     processReadVarint(result);
                 }
             }
             else
             {
                 exceptionHandler(new BcpException.VarintTooBig());
             }
         }
         catch (Exception e)
         {
             exceptionHandler(e);
         }
     };
     try
     {
         stream.BeginRead(buffer, 0, 1, asyncCallback, readState);
     }
     catch (Exception e)
     {
         exceptionHandler(e);
     }
 }
        private void SslRead(IAsyncResult ar)
        {
            if (m_IsDisposed)
            {
                return;
            }

            try
            {
                int byteCount  = -1;
                int bufferSize = m_Buffer.Length;

                m_LastRead   = DateTime.Now;
                byteCount    = m_NetworkStream.EndRead(ar);
                m_BytesRead += byteCount;

                if (!m_HasHeaders || m_RequestType == RequestType.GET)
                {
                    string sBuffer = Encoding.ASCII.GetString(m_Buffer, 0, byteCount);
                    m_ReadData += sBuffer;
                }

                AppendBuffer(m_Buffer, byteCount);
                m_HasHeaders = UpdateUniqueHeaders();

                if (!m_HasHeaders && m_BytesRead > 1024)
                {
                    Program.BlacklistIP(m_RemoteIP, m_ReadData, "No HTTP headers found in the first 1024 bytes");
                    return;
                }

                if (byteCount > 0)
                {
                    if (m_RequestType != RequestType.POST && m_RequestType != RequestType.None)
                    {
                        m_NetworkStream.BeginRead(m_Buffer, 0, bufferSize, new AsyncCallback(SslRead), m_NetworkStream);
                    }
                    else if (m_EndBoundaryIndex == -1)     // as long as we haven't found the end of the stream continue reading
                    {
                        m_NetworkStream.BeginRead(m_Buffer, 0, bufferSize, new AsyncCallback(SslRead), m_NetworkStream);
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                return;
            }

            ProcessRequest(m_ReadData);
        }
예제 #7
0
    void dataRead(IAsyncResult result)
    {
        byte[] buffer = result.AsyncState as byte[];

        string data = ASCIIEncoding.ASCII.GetString(buffer, 0, buffer.Length);

        OnDataRecived.Invoke(data);

        if (!stopReciver)
        {
            buffer = new byte[BufferSize];
            connectionStream.BeginRead(buffer, 0, BufferSize, dataRead, buffer);
        }
    }
 public bool StreamContainsSeqeunce(Stream contentStream)
 {
     int num;
     if (contentStream == null)
     {
         throw new ArgumentNullException("contentStream");
     }
     if (this.FSequence == null)
     {
         throw new ArgumentNullException("sequence");
     }
     if (this.FSequence.Length == 0)
     {
         return false;
     }
     byte[] buffer = new byte[0x40000];
     byte[] buffer2 = new byte[0x40000];
     byte[] buffer3 = buffer;
     byte[] buffer4 = buffer2;
     int offset = 0;
     bool flag = false;
     IAsyncResult asyncResult = contentStream.BeginRead(buffer3, 0, buffer3.Length, null, null);
     do
     {
         if (!base.OnProgress(0))
         {
             break;
         }
         num = contentStream.EndRead(asyncResult);
         if (num > 0)
         {
             buffer3 = Interlocked.Exchange<byte[]>(ref buffer4, buffer3);
             int num3 = offset;
             offset = Math.Min(this.FSequence.Length - 1, num);
             asyncResult = contentStream.BeginRead(buffer3, offset, buffer3.Length - offset, null, null);
             flag = ByteArrayHelper.IndexOf(this.FSequence, buffer4, buffer4.Length) >= 0;
             Array.Copy(buffer4, (num + num3) - offset, buffer3, 0, offset);
         }
         else
         {
             asyncResult = null;
         }
     }
     while ((num > 0) && !flag);
     if (asyncResult != null)
     {
         contentStream.EndRead(asyncResult);
     }
     return flag;
 }
예제 #9
0
        public static void StreamReadAsync(
            Stream stream,
            byte[] buffer,
            int offset,
            int count,
            SynchronizationContextWrapper syncContext,
            Action<int, Exception> callback)
        {
            Exception error = null;
            int length = 0;
            try
            {
                stream.BeginRead(buffer, offset, count,
                    delegate(IAsyncResult ar)
                    {
                        try
                        {
                            length = stream.EndRead(ar);
                        }
                        catch (Exception e)
                        {
                            error = e;
                        }

                        callback(length, error);
                    },
                    null);
            }
            catch (Exception e)
            {
                error = e;
                callback(length, error);
            }
        }
예제 #10
0
        public override IAsyncResult BeginRead(byte [] buffer, int offset, int count,
                                               AsyncCallback cback, object state)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(typeof(RequestStream).ToString());
            }

            int nread = FillFromBuffer(buffer, offset, count);

            if (nread > 0 || nread == -1)
            {
                HttpStreamAsyncResult ares = new HttpStreamAsyncResult();
                ares.Buffer    = buffer;
                ares.Offset    = offset;
                ares.Count     = count;
                ares.Callback  = cback;
                ares.State     = state;
                ares.SynchRead = nread;
                ares.Complete();
                return(ares);
            }

            // Avoid reading past the end of the request to allow
            // for HTTP pipelining
            if (remaining_body >= 0 && count > remaining_body)
            {
                count = (int)Math.Min(Int32.MaxValue, remaining_body);
            }
            return(stream.BeginRead(buffer, offset, count, cback, state));
        }
예제 #11
0
        /// <summary>
        /// Pipes data from one stream to another
        /// </summary>
        /// <param name="input">Stream to read from</param>
        /// <param name="output">Stream to write to</param>
        /// <param name="MaxBufferSize">Size of buffer to use</param>
        /// <returns>Number of bytes piped</returns>
        public static int Pipe(Stream input, Stream output, int MaxBufferSize)
        {
            //Internal buffer are two buffers, each half of allowed buffer size, aligned to 1kb blocks
            int bufferSize = (MaxBufferSize / 2) & ~1023;
            if (bufferSize <= 0) throw new Exception("Specified buffer size to small");

            byte[][] buffer = new byte[2][];
            buffer[0] = new byte[bufferSize];
            buffer[1] = new byte[bufferSize];
            int currentBuffer = 0;

            int r, total=0;
            IAsyncResult asyncRead,asyncWrite;

            //Read first block
            r = input.Read(buffer[currentBuffer], 0, bufferSize);

            //Continue while we're getting data
            while (r > 0)
            {
                //read and write simultaneously
                asyncWrite = output.BeginWrite(buffer[currentBuffer], 0, r, null, null);
                asyncRead = input.BeginRead(buffer[1-currentBuffer], 0, bufferSize, null, null);
                //Wait for both
                output.EndWrite(asyncWrite);
                r = input.EndRead(asyncRead);
                //Switch buffers
                currentBuffer = 1 - currentBuffer;
                //Count bytes
                total += r;
            }

            //Return number of bytes piped
            return total;
        }
예제 #12
0
        public bool Connect()
        {
            try
            {
                // Initialize Packet Factory
                PacketHandler.Initialize();

                // Connect Socket
                m_Socket = new TcpClient(m_ServerIP, m_Port);
                m_Stream = m_Socket.GetStream();
                m_Stream.BeginRead(m_bRecvBuffer, 0, MAX_PACKET_SIZE, new AsyncCallback(EndDataReceive), null);

                if (m_Socket.Connected) {
                    Debugger.Log("Connected to {0} on {1}", m_ServerIP, m_Port);
                } else {
                    Disconnect();
                    throw new ApplicationException("Failed to connect to server");
                }

                return true;
            }
            catch(Exception e)
            {
                Debugger.Log (Debugger.LogLevel.Info, "SocketServer", "Connect: {0}", e.Message);
            }
            return false;
        }
예제 #13
0
        static void Main(string[] args)
        {
            _readBuffer = new byte[960];
            Console.WriteLine("Opening \"{0}\" for playback", OpenALHelper.PlaybackDevices[0].DeviceName);
            Console.WriteLine("Opening \"{0}\" for capture", OpenALHelper.CaptureDevices[0].DeviceName);

            _playback = OpenALHelper.PlaybackDevices[0].OpenStream(48000, OpenALAudioFormat.Mono16Bit);
            _playback.Listener.Position = new Vector3() { X = 0.0f, Y = 0.0f, Z = 0.0f };
            _playback.Listener.Velocity = new Vector3() { X = 0.0f, Y = 0.0f, Z = 0.0f };
            _playback.Listener.Orientation = new Orientation()
                {
                    At = new Vector3() { X = 0.0f, Y = 0.0f, Z = 1.0f },
                    Up = new Vector3() { X = 0.0f, Y = 1.0f, Z = 0.0f }
                };
            _playback.ALPosition = new Vector3() { X = 0.0f, Y = 0.0f, Z = 0.0f };
            _playback.Velocity = new Vector3() { X = 0.0f, Y = 0.0f, Z = 0.0f };
            _capture = OpenALHelper.CaptureDevices[0].OpenStream(48000, OpenALAudioFormat.Mono16Bit, 10);
            _capture.BeginRead(_readBuffer, 0, _readBuffer.Length, Callback, null);

            while (true)
            {
                PrintUI();
                if (ProcessInput())
                    break;
            }

            _playback.Close();
            _playback.Dispose();
            _capture.Close();
            _capture.Dispose();
        }
예제 #14
0
        private AsyncComparer(Stream source, byte[] expected, Action<bool> completed)
        {
            _expected = expected;
            _src = source;
            _completed = completed;

            _src.BeginRead(_buffer, 0, ChunkSize, OnRead, null);
        }
예제 #15
0
 public void Connect()
 {
     _channel = StreamFactory.CreateStream(_connString);
     readOp = _channel.BeginRead(headerBuffer, 0, 1, callback, null);
     // Give the qosManager a handle to the streams
     qosManager.SetStreamManager(this);
     _connected = true;
 }
예제 #16
0
        private static string ReadDataFromStream(Stream str)
        {
            var buff = new byte[10000];
            var asyncResult = str.BeginRead(buff, 0, buff.Length, null, null);

            var bytesRead = str.EndRead(asyncResult);
            return Encoding.UTF8.GetString(buff, 0, bytesRead);
        }
예제 #17
0
 public IAsyncResult BeginRead( Stream stream, AsyncCallback callback )
 {
     if ( IsFull ) {
         Debug.Print( "FancyBuffer.BeginRead: buffer is full" );
         throw new Exception( "Read buffer is full." );
     }
     _stream = stream;
     return _stream.BeginRead( Buffer, Offset, Available, callback, this );
 }
        private IAsyncResult OnEnter(Object sender, EventArgs e, AsyncCallback cb, Object state) {
            Debug.Assert(_inputStream == null);
            _app = (HttpApplication)sender;
            HttpContext context = _app.Context;
            HttpRequest request = context.Request;
            HttpWorkerRequest wr = context.WorkerRequest;
            HttpAsyncResult httpAsyncResult = new HttpAsyncResult(cb, state);
            AsyncPreloadModeFlags asyncPreloadMode = context.AsyncPreloadMode;
            int contentLength;
            bool isForm = false;
            bool isFormMultiPart = false;

            if (asyncPreloadMode == AsyncPreloadModeFlags.None
                || request.ReadEntityBodyMode != ReadEntityBodyMode.None
                || wr == null
                || !wr.SupportsAsyncRead
                || !wr.HasEntityBody()
                || wr.IsEntireEntityBodyIsPreloaded()
                || context.Handler == null
                || context.Handler is TransferRequestHandler
                || context.Handler is DefaultHttpHandler
                || (contentLength = request.ContentLength) > RuntimeConfig.GetConfig(context).HttpRuntime.MaxRequestLengthBytes
                || ((isForm = StringUtil.StringStartsWithIgnoreCase(request.ContentType, "application/x-www-form-urlencoded"))
                    && (asyncPreloadMode & AsyncPreloadModeFlags.Form) != AsyncPreloadModeFlags.Form)
                || ((isFormMultiPart = StringUtil.StringStartsWithIgnoreCase(request.ContentType, "multipart/form-data"))
                    && (asyncPreloadMode & AsyncPreloadModeFlags.FormMultiPart) != AsyncPreloadModeFlags.FormMultiPart)
                || !isForm && !isFormMultiPart && (asyncPreloadMode & AsyncPreloadModeFlags.NonForm) != AsyncPreloadModeFlags.NonForm
                ) {
                Debug.Trace("AsyncPreload", " *** AsyncPreload skipped *** ");
                httpAsyncResult.Complete(true, null, null);
                return httpAsyncResult;
            }

            Debug.Trace("AsyncPreload", " *** AsyncPreload started *** ");
            try {
                if (_callback == null) {
                    _callback = new AsyncCallback(OnAsyncCompletion);
                }
                _inputStream = request.GetBufferedInputStream();
                byte[] buffer = _app.EntityBuffer;
                int bytesRead = 0;
                // loop to prevent recursive calls and potential stack overflow if/when it completes synchronously
                do {
                    IAsyncResult readAsyncResult = _inputStream.BeginRead(buffer, 0, buffer.Length, _callback, httpAsyncResult);
                    if (!readAsyncResult.CompletedSynchronously) {
                        return httpAsyncResult;
                    }
                    bytesRead = _inputStream.EndRead(readAsyncResult);
                } while (bytesRead != 0);
            }
            catch {
                Reset();
                throw;
            }
            httpAsyncResult.Complete(true, null, null);
            return httpAsyncResult;
        }
		public AsyncStreamReader(Stream stream, Action<byte[]> completed, int bufferSize)
		{
			_bufferSize = bufferSize;
			_buffer = new byte[_bufferSize];
			_completed = completed;
			_stream = stream;
			_all = new List<byte>();

			_stream.BeginRead(_buffer, 0, _bufferSize, Callback, this);
		}
		public static void Copy( Stream in_sourceStream, Stream out_destStream ) {
			Streams streams = new Streams( in_sourceStream, out_destStream );

			IAsyncResult ar = in_sourceStream.BeginRead(
				streams.Buffer, 
				0, 
				streams.BufferSize, 
				new AsyncCallback( CopyStreamCallback ), 
				streams
			);
		}
예제 #21
0
 public override IAsyncResult BeginRead(
     byte[] buffer,
     int offset,
     int count,
     AsyncCallback callback,
     object state
     )
 {
     Trace.WriteLine("TraceStream", String.Format("BeginRead(): offset({0}), count({1})", offset, count));
     return(m_in.BeginRead(buffer, offset, count, callback, state));
 }
예제 #22
0
        /// <summary>
        /// Creates a redirector between the two streams
        /// </summary>
        public StreamRedirect(Stream from, Stream to, string connInfo)
		{
            _logger = null;
            _from = from;
			_to = to;
			_connectionInfo = connInfo;

			_closed = new ManualResetEvent(false);

			_buffer = new byte[BUFF_SIZE];
			_result = _from.BeginRead(_buffer, 0, _buffer.Length, OnRead, null);
        }
예제 #23
0
 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
 {
     _lock.AcquireReaderLock();
     try {
         if (this.IsClosed)
         {
             throw new ObjectDisposedException(null);
         }
     } finally {
         _lock.ReleaseReaderLock();
     }
     return(_innerStream.BeginRead(buffer, offset, count, callback, state));
 }
        private static AsyncEvent StreamCopy(Stream src, Stream dst, Func<bool> assertContinuation, Action onException = null, Action<int> onProgress = null)
        {
            var evt = new AsyncEvent(false, false);
            var exception = false;
            AsyncCallback cb = null;
            cb = (ar) =>
            {
                var count = src.EndRead(ar);
                var readed = (byte[])ar.AsyncState;
                if (exception) return;

                if (count != 0)
                {
                    lock (evt)
                    {
                        if (exception) return;
                        var newArray = new byte[BLOCK_SIZE];
                        if (!assertContinuation())
                         return;

                        if (onProgress != null)
                            onProgress(count);

                        src.BeginRead(newArray, 0, BLOCK_SIZE, cb, newArray);
                        try
                        {
                            dst.Write(readed, 0, count);
                        }
                        catch (Exception e)
                        {
                            exception = true;
                            if(onException != null)
                                onException();

                        }
                    }
                }
                else
                {
                    lock (evt)
                    {
                        src.Close();
                        evt.Set();
                    }
                }
            };
            var startBuffer = new byte[BLOCK_SIZE];
            src.BeginRead(startBuffer, 0, BLOCK_SIZE, cb, startBuffer);
            return evt;
        }
예제 #25
0
        protected void StartRecording()
        {
            //Create or overwrite tempfile
            this.TempFile = File.Create(PathSettings.TempFilePath);

            //Getting stream
            WebRequest      wReq = WebRequest.Create(this.StreamURL);
            HttpWebResponse hRes = (HttpWebResponse)wReq.GetResponse();

            System.IO.Stream RadioStream = hRes.GetResponseStream();

            //Start reading process
            this.ReadHandle = RadioStream.BeginRead(this.Buffer, 0, this.Buffer.Length, new System.AsyncCallback(this.TempSave), RadioStream);
        }
예제 #26
0
        public AsyncStreamReader(Stream aStream, Encoding anEncoding, EventHandler<LineReceivedEventArgs> aLineReceivedCallback)
        {
            if (aStream == null)
            throw new ArgumentNullException("aStream");
              if (anEncoding == null)
            throw new ArgumentNullException("anEncoding");
              if (!aStream.CanRead)
            throw new ArgumentException("Stream does not support reading");

              theBaseStream = aStream;
              theEncoding = anEncoding;
              theLineReaded = aLineReceivedCallback;
              theBaseStream.BeginRead(theReadBuffer, 0, theReadBuffer.Length, AsyncCallback, null);
        }
		private void ReadAsync(Stream responseStream)
		{
			Task.Factory.FromAsync<int>((callback, o) => responseStream.BeginRead(buffer, posInBuffer, buffer.Length- posInBuffer, callback, o),
			                       responseStream.EndRead, null)
								   .ContinueWith(task =>
								   {
									   var read = task.Result;
									   if (read == 0)// will for a reopening of the connection
										   throw new EndOfStreamException();
									   // find \r\n in newly read range

									   var startPos = 0;
									   byte prev = 0;
									   bool foundLines = false;
									   for (int i = posInBuffer; i < posInBuffer + read; i++)
									   {
										   if (prev == '\r' && buffer[i] == '\n')
										   {
											   foundLines = true;
											   // yeah, we found a line, let us give it to the users
											   var data = Encoding.UTF8.GetString(buffer, startPos, i - 1 - startPos);
											   startPos = i + 1;
										   	Dispatcher.BeginInvoke(() =>
										   	{
										   		ServerResults.Text += data + Environment.NewLine;
										   	});
										   }
										   prev = buffer[i];
									   }
									   posInBuffer += read;
									   if (startPos >= posInBuffer) // read to end
									   {
										   posInBuffer = 0;
										   return;
									   }
									   if (foundLines == false)
										   return;

									   // move remaining to the start of buffer, then reset
									   Array.Copy(buffer, startPos, buffer, 0, posInBuffer - startPos);
									   posInBuffer -= startPos;
								   })
								   .ContinueWith(task =>
								   {
									   if (task.IsFaulted)
									   	return;
									   ReadAsync(responseStream);
								   });
		}
예제 #28
0
		public void StartReceive(Stream stream)
		{
			if (stream == null)
				throw new ArgumentNullException("stream");
			if (this.stream != null)
				throw new InvalidOperationException("StartReceive can be called only once.");
			this.stream = stream;
			try {
				stream.BeginRead(buffer, 0, buffer.Length, OnReceive, null);
			} catch (ObjectDisposedException) {
				OnConnectionLost();
			} catch (IOException) {
				OnConnectionLost();
			}
		}
예제 #29
0
 public void AsyncFileReadTestCase()
 {
     buffer = new Byte[BufferSize];
     myCallBack = new AsyncCallback(this.OnCompletedRead);
     isoReaderStreamCallBack = File.OpenRead(@"/Users/tomohiro/gitrepo/study/CSharp-Study/kinmokusei/AsyncText.txt");
     isoReaderStreamCallBack.BeginRead( // 非同期読み込み
                           buffer, // 読み込み結果を格納するバッファ
                           0, // 読み込みの始点
                           buffer.Length, // バッファのサイズ
                           myCallBack, // 読み込み完了時のコールバック
                           null // 状態を取得するためのオブジェクト
                           );
     for( int i = 0; i < 100; i++ ) Console.WriteLine("i={0}", i);
     isoReaderStreamCallBack.Close ();
 }
예제 #30
0
        /// <summary>
        /// Read from a stream asynchronously.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="length">The number of bytes to read.</param>
        /// <param name="completed">The completed action.</param>
        /// <param name="error">The error action.</param>
        public static void ReadAsync(this System.IO.Stream stream, int length, Action <byte[]> completed, Action <Exception> error)
        {
            var buff = new byte[length];

            stream.BeginRead(
                buff,
                0,
                length,
                ar =>
            {
                try
                {
                    byte[] bytes = null;
                    try
                    {
                        var len = stream.EndRead(ar);
                        bytes   = len < 1
                                  ? new byte[0]
                                  : len < length
                                    ? stream.ReadBytes(buff, len, length - len)
                                    : buff;
                    }
                    catch
                    {
                        bytes = new byte[0];
                    }

                    if (completed != null)
                    {
                        completed(bytes);
                    }
                }
                catch (Exception ex)
                {
                    if (error != null)
                    {
                        error(ex);
                    }
                }
            },
                null);
        }
예제 #31
0
        private void startStreamAsyncRead()
        {
            byte[] buffer = new byte[1000000];

            if (this.isConnected() == false)
            {
                System.Diagnostics.Debug.WriteLine("isconnected is false");
                this.OnServerDisconnected(new ServerEventArgs(this.tcpClient));
                this.Disconnect();
                return;
            }

            if (useExplicitStreams)
            {
                AsyncCallback networkReadCallback = new AsyncCallback(dataReceivedSsh);
                sshStreamRead.BeginRead(buffer, 0, 100000, networkReadCallback, buffer);
            }
            else
            {
                if (!tcpStream.CanRead)
                {
                    return;                     /* program probably died */
                }
                AsyncCallback networkReadCallback = new AsyncCallback(dataReceived);
                try
                {
                    if (tcpStreamGzipRead != null)
                    {
                        tcpStreamGzipRead.BeginRead(buffer, 0, 1000000, networkReadCallback, buffer);
                    }
                    else
                    {
                        tcpStream.BeginRead(buffer, 0, 1000000, networkReadCallback, buffer);
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Disconnected?");
                }
                // tcpStream.Read(buffer, p, p_3);
            }
        }
예제 #32
0
파일: Body.cs 프로젝트: bvanderveen/gate
        public static BodyAction FromStream(Stream stream)
        {
            return (next, error, complete) =>
            {
                var buffer = new byte[4096];
                var continuation = new AsyncCallback[1];
                bool[] stopped = {false};
                continuation[0] = result =>
                {
                    if (result != null && result.CompletedSynchronously) return;
                    try
                    {
                        for (;;)
                        {
                            if (result != null)
                            {
                                var count = stream.EndRead(result);
                                if (stopped[0]) return;
                                if (count <= 0)
                                {
                                    complete();
                                    return;
                                }
                                var data = new ArraySegment<byte>(buffer, 0, count);
                                if (next(data, () => continuation[0](null))) return;
                            }

                            if (stopped[0]) return;
                            result = stream.BeginRead(buffer, 0, buffer.Length, continuation[0], null);
                            if (!result.CompletedSynchronously) return;
                        }
                    }
                    catch (Exception ex)
                    {
                        error(ex);
                    }
                };
                continuation[0](null);
                return () => { stopped[0] = true; };
            };
        }
예제 #33
0
      private static IEnumerator<Int32> CopyStream(AsyncEnumerator<Int64> ae, Stream source, Stream destination, Int32 bufferSize, Action<Int64> reportProgress) {
         Byte[] buffer = new Byte[bufferSize];
         Int64 totalBytesRead = 0;
         while (true) {
            ae.SetOperationTag("Reading from source stream");
            // Read whichever is smaller (number of bytes left to read OR the buffer size)
            source.BeginRead(buffer, 0, buffer.Length, ae.End(), null);
            yield return 1;
            Int32 bytesReadThisTime = source.EndRead(ae.DequeueAsyncResult());
            totalBytesRead += bytesReadThisTime;

            ae.SetOperationTag("Writing to destination stream");
            destination.BeginWrite(buffer, 0, bytesReadThisTime, ae.End(), null);
            yield return 1;
            destination.EndWrite(ae.DequeueAsyncResult());

            if (reportProgress != null) reportProgress(totalBytesRead);
            if (bytesReadThisTime < buffer.Length) break;
         }
         ae.Result = totalBytesRead;
      }
예제 #34
0
        public static IEnumerable<CompletionPort> ReadBytesAsync(AsyncMachine<byte[]> machine, Stream stream, int length)
        {
            var attributeHelper = new AttributeHelper<VhdHeader>();
            var buffer = new byte[length];

            int readCount = 0;
            int remaining = length;
            while (remaining > 0)
            {
                stream.BeginRead(buffer, readCount, remaining, machine.CompletionCallback, null);
                yield return CompletionPort.SingleOperation;
                var currentRead = stream.EndRead(machine.CompletionResult);
                if (currentRead == 0)
                {
                    break;
                }
                readCount += currentRead;
                remaining -= currentRead;
            }
            machine.ParameterValue = buffer;
            yield break;
        }
예제 #35
0
        public void CopyStream(Stream media)
        {
            // Make sure the stream is ready first.
            int tries = 10000; // 10 Seconds
            do
            {
                if (this.IsReady)
                    break;

                System.Threading.Thread.Sleep(1);
            } while (--tries != 0);

            if (IsReady)
            {
                buffer = new byte[0x1000];

                media.BeginRead(buffer, 0, buffer.Length, MediaReadAsyncCallback, media);
            }
            else
            {
                throw new Exception("Pipe Stream isn't ready.");
            }
        }
예제 #36
0
        public void Connect(IPAddress address)
        {
            m_Address = address;

            try
            {
                m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                m_Socket.Connect(new IPEndPoint(address, 48888));

                m_NetworkStream = new NetworkStream(m_Socket);
                m_NetworkStream.BeginRead(m_ReadBuffer, 0, READ_BUFFER_SIZE, m_cbDataRead, null);

                parent.PostMessage("Successfully connected to robot host.");
            }
            catch(Exception ex)
            {
                parent.PostMessage("Error connecting to robot host.\r\n  " + ex.Message);

                m_Socket = null;
                m_NetworkStream = null;
            }

            parent.UpdateStatus();
        }
예제 #37
0
    private bool VerifyReadException(System.IO.Stream serialStream, Type expectedException)
    {
        bool retValue = true;

        System.IAsyncResult readAsyncResult;

        try
        {
            readAsyncResult = serialStream.BeginRead(new byte[defaultByteArraySize], 0, defaultByteArraySize, null, null);
            readAsyncResult.AsyncWaitHandle.WaitOne();

            Console.WriteLine("ERROR!!!: No Excpetion was thrown");
            retValue = false;
        }
        catch (System.Exception e)
        {
            if (e.GetType() != expectedException)
            {
                Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException);
                retValue = false;
            }
        }
        return(retValue);
    }
예제 #38
0
 public override void recv(byte[] buffer, int offset, int size,
                           ResultHandler rh)
 {
     mStream.BeginRead(buffer, offset, size, new AsyncCallback(RecvCallback), rh);
 }
예제 #39
0
 /// <summary>
 /// Begins an asynchronous read operation.
 /// </summary>
 /// <param name="stream">The stream to read from.</param>
 /// <param name="buffer">The buffer to read the data into.</param>
 /// <param name="callback">The callback to which a System.IO.AsyncStreamOperationState object is passed.</param>
 public static void BeginRead(this Stream stream, byte[] buffer, AsyncCallback callback)
 {
     stream.BeginRead(buffer, 0, buffer.Length, callback, new StreamAsyncState(stream, buffer));
 }
예제 #40
0
 /// <inheritdoc />
 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
 {
     return(_stream.BeginRead(buffer, offset, count, callback, state));
 }
예제 #41
0
파일: SshExe.cs 프로젝트: BHandal/Minion
        public int RunCommand(string command, Stream stdoutOutput, TextWriter stderrOutput)
        {
            m_channel = GetChannelExec(command);

            System.IO.Stream stdout = m_channel.getInputStream();

            System.IO.Stream stderr = ((ChannelExec)m_channel).getErrStream();

            m_channel.connect();



            byte[] stdoutByteBuffer = new byte[1024];

            byte[] stderrByteBuffer = new byte[32];



            ////////////////////////////////////////////////////////////////////////////

            bool stdoutIsExhausted = false;

            AsyncCallback stdoutReadCallback = null;

            stdoutReadCallback = readResult =>
            {
                int bytesRead = stdout.EndRead(readResult);

                if (bytesRead > 0)
                {
                    stdoutOutput.Write(

                        stdoutByteBuffer,

                        0,

                        bytesRead

                        );

                    stdout.BeginRead(stdoutByteBuffer, 0, stdoutByteBuffer.Length, stdoutReadCallback, null);
                }

                else if (bytesRead < 0)
                {
                    stdoutOutput.Flush();

                    stdoutIsExhausted = true;
                }
            };

            ////////////////////////////////////////////////////////////////////////////

            bool stderrIsExhausted = false;

            AsyncCallback stderrReadCallback = null;

            stderrReadCallback = readResult =>
            {
                int bytesRead = stderr.EndRead(readResult);

                if (bytesRead > 0)
                {
                    string text = System.Text.ASCIIEncoding.ASCII.GetString(stderrByteBuffer, 0, bytesRead);

                    text = text.Replace("\n", Environment.NewLine);

                    stderrOutput.Write(text);

                    stderr.BeginRead(stderrByteBuffer, 0, stderrByteBuffer.Length, stderrReadCallback, null);
                }

                else if (bytesRead < 0)
                {
                    stderrIsExhausted = true;
                }
            };

            ////////////////////////////////////////////////////////////////////////////



            stdout.BeginRead(stdoutByteBuffer, 0, stdoutByteBuffer.Length, stdoutReadCallback, null);

            stderr.BeginRead(stderrByteBuffer, 0, stderrByteBuffer.Length, stderrReadCallback, null);



            while (!(stdoutIsExhausted && stderrIsExhausted))
            {
                // empty loop; wait until reads are complete before returning
            }



            m_channel.disconnect();

            return(m_channel.getExitStatus());
        }
예제 #42
-3
        public static IAsyncResult BeginReadStreamToEnd(Stream stream, byte[] buffer, int offset, int count,
			AsyncCallback callback, Object state)
        {
            byte[] tempBuffer = new byte[count];
            ByteArrayAsyncResult result = new ByteArrayAsyncResult(callback, state, buffer, offset, tempBuffer);
            ByteArrayAsyncState asyncState = new ByteArrayAsyncState();
            asyncState.Result = result;
            asyncState.Stream = stream;
            stream.BeginRead(tempBuffer, 0, count, OnRead, asyncState);
            return result;
        }
예제 #43
-5
        public void Start()
        {
            Console.WriteLine("Sensor: Starting Speed Sensor");

            port.Open();
            stream = port.BaseStream;

            // C# serial port class is dangerous, only the BaseStream is safe
            // http://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport
            stream.BeginRead(recvBuffer, 0, recvBuffer.Length, OnRecv, null);
        }