public StreamByteCounter(Stream src) { AsyncCallback onEndRead = null; onEndRead = delegate(IAsyncResult ar) { int c = src.EndRead(ar); if (c != 0) { lock(this) { pendingReads++; } // // For each read, we must allocate a new buffer. // byte[] nb = new byte[CHUNK_SIZE]; src.BeginRead(nb, 0, nb.Length, onEndRead, nb); // // The buffer of the current read is passed through the // IAsyncResult.AsyncState property. // byte[] cb = (byte[])ar.AsyncState; // // Increment occurrence counters. // lock(this) { for (int i = 0; i < c; i++) { counters[cb[i]]++; } } } // // The data of the current read processed; so, decrement // the pending counter, and if the counter reaches zero, // signal the "done" event. // lock(this) { if (--pendingReads == 0) { done.Set(); } } }; // // Allocate the buffer for the first read, and issue it. // byte[] fb = new byte[CHUNK_SIZE]; pendingReads = 1; src.BeginRead(fb, 0, fb.Length, onEndRead, fb); }
public void Start() { var theStream = client.GetStream(); if (isSecureClient) { X509Certificate2 certificate = new X509Certificate2( Path.Combine( Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "MSNServer.p12"), "1234"); SslStream sslstream = new SslStream(theStream, false, HandleRemoteCertificateValidationCallback); stream = sslstream; try { sslstream.AuthenticateAsServer(certificate); } catch (IOException ex) { Console.WriteLine("AuthenticateAsServer failed: " + ex.Message); Close(); } } else { stream = theStream; } if (stream?.CanRead ?? false) { stream?.BeginRead(tempBuffer, 0, tempBuffer.Length, ReadCallback, null); } }
public static bool ReadBeyondEndTest(Stream s) { Console.WriteLine("Read Beyond End test on "+s.GetType().Name); byte[] bytes = new byte[10]; for(int i=0; i<bytes.Length; i++) bytes[i] = (byte) i; s.Seek(5, SeekOrigin.End); if (s.Position != s.Length + 5) { iCountErrors++; throw new Exception("Position is incorrect! Seek(5, SeekOrigin.End) should leave us at s.Length + 5, but got: "+s.Position); } int numRead = s.Read(bytes, 0, bytes.Length); if (numRead != 0) { iCountErrors++ ; throw new Exception("Reading from past end of stream is broken! Expected 0, got: "+numRead); } for(int i=0; i<bytes.Length; i++) { if (bytes[i] != (byte) i) { iCountErrors++ ; throw new Exception("Error in byte[] - Read overwrote it! pos: "+i+" got: "+bytes[i]); } } numRead = s.ReadByte(); if (numRead != -1) { iCountErrors++ ; throw new Exception("ReadByte didn't return -1! got: "+numRead); } IAsyncResult ar = s.BeginRead(bytes, 0, bytes.Length, null, null); numRead = s.EndRead(ar); if (numRead != 0) { iCountErrors++ ; throw new Exception("Reading from past end of stream with BeginRead is broken! Expected 0, got: "+numRead); } for(int i=0; i<bytes.Length; i++) if (bytes[i] != (byte) i) { iCountErrors++ ; throw new Exception("Error in byte[] - BeginRead overwrote it! pos: "+i+" got: "+bytes[i]); } return true; }
private void RunReadLoop(Stream localReadPipe, Stream localWritePipe, ConcurrentQueue <INodePacket> localPacketQueue, AutoResetEvent localPacketAvailable, AutoResetEvent localTerminatePacketPump) { // Ordering of the wait handles is important. The first signalled wait handle in the array // will be returned by WaitAny if multiple wait handles are signalled. We prefer to have the // terminate event triggered so that we cannot get into a situation where packets are being // spammed to the endpoint and it never gets an opportunity to shutdown. CommunicationsUtilities.Trace("Entering read loop."); byte[] headerByte = new byte[5]; #if FEATURE_APM IAsyncResult result = localReadPipe.BeginRead(headerByte, 0, headerByte.Length, null, null); #else Task <int> readTask = CommunicationsUtilities.ReadAsync(localReadPipe, headerByte, headerByte.Length); #endif bool exitLoop = false; do { // Ordering is important. We want packetAvailable to supercede terminate otherwise we will not properly wait for all // packets to be sent by other threads which are shutting down, such as the logging thread. WaitHandle[] handles = new WaitHandle[] { #if FEATURE_APM result.AsyncWaitHandle, #else ((IAsyncResult)readTask).AsyncWaitHandle, #endif localPacketAvailable, localTerminatePacketPump }; int waitId = WaitHandle.WaitAny(handles); switch (waitId) { case 0: { int bytesRead = 0; try { #if FEATURE_APM bytesRead = localReadPipe.EndRead(result); #else bytesRead = readTask.Result; #endif } catch (Exception e) { // Lost communications. Abort (but allow node reuse) CommunicationsUtilities.Trace("Exception reading from server. {0}", e); ExceptionHandling.DumpExceptionToFile(e); ChangeLinkStatus(LinkStatus.Inactive); exitLoop = true; break; } if (bytesRead != headerByte.Length) { // Incomplete read. Abort. if (bytesRead == 0) { CommunicationsUtilities.Trace("Parent disconnected abruptly"); } else { CommunicationsUtilities.Trace("Incomplete header read from server. {0} of {1} bytes read", bytesRead, headerByte.Length); } ChangeLinkStatus(LinkStatus.Failed); exitLoop = true; break; } NodePacketType packetType = (NodePacketType)Enum.ToObject(typeof(NodePacketType), headerByte[0]); try { _packetFactory.DeserializeAndRoutePacket(0, packetType, BinaryTranslator.GetReadTranslator(localReadPipe, _sharedReadBuffer)); } catch (Exception e) { // Error while deserializing or handling packet. Abort. CommunicationsUtilities.Trace("Exception while deserializing packet {0}: {1}", packetType, e); ExceptionHandling.DumpExceptionToFile(e); ChangeLinkStatus(LinkStatus.Failed); exitLoop = true; break; } #if FEATURE_APM result = localReadPipe.BeginRead(headerByte, 0, headerByte.Length, null, null); #else readTask = CommunicationsUtilities.ReadAsync(localReadPipe, headerByte, headerByte.Length); #endif } break; case 1: case 2: try { // Write out all the queued packets. INodePacket packet; while (localPacketQueue.TryDequeue(out packet)) { var packetStream = _packetStream; packetStream.SetLength(0); ITranslator writeTranslator = BinaryTranslator.GetWriteTranslator(packetStream); packetStream.WriteByte((byte)packet.Type); // Pad for packet length _binaryWriter.Write(0); // Reset the position in the write buffer. packet.Translate(writeTranslator); int packetStreamLength = (int)packetStream.Position; // Now write in the actual packet length packetStream.Position = 1; _binaryWriter.Write(packetStreamLength - 5); localWritePipe.Write(packetStream.GetBuffer(), 0, packetStreamLength); } } catch (Exception e) { // Error while deserializing or handling packet. Abort. CommunicationsUtilities.Trace("Exception while serializing packets: {0}", e); ExceptionHandling.DumpExceptionToFile(e); ChangeLinkStatus(LinkStatus.Failed); exitLoop = true; break; } if (waitId == 2) { CommunicationsUtilities.Trace("Disconnecting voluntarily"); ChangeLinkStatus(LinkStatus.Failed); exitLoop = true; } break; default: ErrorUtilities.ThrowInternalError("waitId {0} out of range.", waitId); break; } }while (!exitLoop); }
/// <summary> ///异步复制文件 /// </summary> /// <param name="ar"></param> private void AsyncCopyFile(IAsyncResult ar) { //Invoke(new System.DeleSynchProgressBar); int readedLength; // 更新progressBar1 MethodInvoker m = SynchProgressBar; try { //判断stream是否可读(是否已被关掉) if (stream.CanRead) { // 锁定 FileStream lock (stream) { readedLength = stream.EndRead(ar); // 等到挂起的异步读取完成 } } else { topathnum++; copycircle(); m.BeginInvoke(null, null); return; } // 写入磁盘 var fsWriter = new FileStream(topath + "\\" + filename, FileMode.Append, FileAccess.Write); fsWriter.Write(buffer, 0, buffer.Length); fsWriter.Close(); // 当前位置 position += readedLength; // 更新progressBar1 m.BeginInvoke(null, null); if (position >= totalSize) // 读取完毕 { stream.Close(); //关闭 topathnum++; copycircle(); return; } if (stream.CanRead) { lock (stream) { int leftSize = totalSize - position; if (leftSize < BUFFER_SIZE) { buffer = new byte[leftSize]; } stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(AsyncCopyFile), null); } } else { topathnum++; m.BeginInvoke(null, null); copycircle(); return; } } catch (Exception e) { MessageBox.Show("复制文件出错!" + e.ToString()); topathnum++; m.BeginInvoke(null, null); copycircle(); } }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return(m_s.BeginRead(buffer, offset, count, callback, state)); }
private void OnReceive(IAsyncResult ar) { try { int bytesRead = Stream.EndRead(ar); if (bytesRead == 0) { Disconnect(SocketError.ConnectionReset); return; } _bytesLeft += bytesRead; if (_bytesLeft > _buffer.Length) { #if DEBUG throw new BadRequestException("Too large HTTP header: " + Encoding.UTF8.GetString(_buffer, 0, bytesRead)); #else throw new BadRequestException("Too large HTTP header: " + _bytesLeft); #endif } #if DEBUG #pragma warning disable 219 string temp = Encoding.ASCII.GetString(_buffer, 0, _bytesLeft); LogWriter.Write(this, LogPrio.Trace, "Received: " + temp); #pragma warning restore 219 #endif int offset = _parser.Parse(_buffer, 0, _bytesLeft); if (Stream == null) { return; // "Connection: Close" in effect. } // try again to see if we can parse another message (check parser to see if it is looking for a new message) int oldOffset = offset; while (_parser.CurrentState == RequestParserState.FirstLine && offset != 0 && _bytesLeft - offset > 0) { #if DEBUG temp = Encoding.ASCII.GetString(_buffer, offset, _bytesLeft - offset); LogWriter.Write(this, LogPrio.Trace, "Processing: " + temp); #endif offset = _parser.Parse(_buffer, offset, _bytesLeft - offset); if (Stream == null) { return; // "Connection: Close" in effect. } } // need to be able to move prev bytes, so restore offset. if (offset == 0) { offset = oldOffset; } // copy unused bytes to the beginning of the array if (offset > 0 && _bytesLeft > offset) { Buffer.BlockCopy(_buffer, offset, _buffer, 0, _bytesLeft - offset); } _bytesLeft -= offset; if (Stream != null && Stream.CanRead) { Stream.BeginRead(_buffer, _bytesLeft, _buffer.Length - _bytesLeft, OnReceive, null); } else { _log.Write(this, LogPrio.Warning, "Could not read any more from the socket."); Disconnect(SocketError.Success); } } catch (BadRequestException err) { LogWriter.Write(this, LogPrio.Warning, "Bad request, responding with it. Error: " + err); try { Respond("HTTP/1.0", HttpStatusCode.BadRequest, err.Message); } catch (Exception err2) { LogWriter.Write(this, LogPrio.Fatal, "Failed to reply to a bad request. " + err2); } Disconnect(SocketError.NoRecovery); } catch (IOException err) { LogWriter.Write(this, LogPrio.Debug, "Failed to end receive: " + err.Message); if (err.InnerException is SocketException) { Disconnect((SocketError)((SocketException)err.InnerException).ErrorCode); } else { Disconnect(SocketError.ConnectionReset); } } catch (ObjectDisposedException err) { LogWriter.Write(this, LogPrio.Debug, "Failed to end receive : " + err.Message); Disconnect(SocketError.NotSocket); } catch (NullReferenceException err) { LogWriter.Write(this, LogPrio.Debug, "Failed to end receive : NullRef: " + err.Message); Disconnect(SocketError.NoRecovery); } catch (Exception err) { LogWriter.Write(this, LogPrio.Debug, "Failed to end receive: " + err.Message); Disconnect(SocketError.NoRecovery); } }
/// <summary> /// Begins an asynchronous read operation. /// </summary> /// <param name="buffer">The buffer to read the data into. </param> /// <param name="offset"> /// The byte offset in buffer at which to begin writing data read from the stream. /// </param> /// <param name="count">The maximum number of bytes to read. </param> /// <param name="callback"> /// An optional asynchronous callback, to be called when the read is complete. /// </param> /// <param name="state"> /// A user-provided object that distinguishes this particular /// asynchronous read request from other requests. /// </param> /// <returns> /// An IAsyncResult that represents the asynchronous read, /// which could still be pending. /// </returns> public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { CheckClosed(); return(BaseStream.BeginRead(buffer, offset, count, callback, state)); }
/// <summary> /// Interpret incoming data. /// </summary> /// <param name="ar"></param> private void OnReceive(IAsyncResult ar) { // been closed by our side. if (Stream == null) { return; } _context = this; HttpFactory.Current = HttpFactory; try { int bytesLeft = Stream.EndRead(ar); if (bytesLeft == 0) { _logger.Trace("Client disconnected."); Close(); return; } _logger.Debug(Socket.RemoteEndPoint + " received " + bytesLeft + " bytes."); if (bytesLeft < 5000) { string temp = Encoding.ASCII.GetString(_buffer, 0, bytesLeft); _logger.Trace(temp); } int offset = ParseBuffer(bytesLeft); bytesLeft -= offset; if (bytesLeft > 0) { _logger.Warning("Moving " + bytesLeft + " from " + offset + " to beginning of array."); Buffer.BlockCopy(_buffer, offset, _buffer, 0, bytesLeft); } if (Stream == null) { Close(); } else { Stream.BeginRead(_buffer, 0, _buffer.Length - offset, OnReceive, null); } } catch (ParserException err) { _logger.Warning(err.ToString()); var response = new Response("HTTP/1.0", HttpStatusCode.BadRequest, err.Message); var generator = HttpFactory.Current.Get <ResponseWriter>(); generator.Send(this, response); Close(); } catch (Exception err) { if (!(err is IOException)) { _logger.Error("Failed to read from stream: " + err); UnhandledException(this, new ExceptionEventArgs(err)); } Close(); } }
// // File copy using APM performs asynchronous reads and asynchronous // write operations. // static long ApmFileCopy2(Stream src, Stream dst) { var done = new ManualResetEventSlim(false); long fileSize = 0; IOException ioex = null; int pendingWrites = 1; // Account for the last read of 0 bytes. AsyncCallback onReadCompleted = null, onWriteCompleted = null; onReadCompleted = delegate (IAsyncResult ar) { int bytesRead = 0; byte[] _rbuffer = (byte[])ar.AsyncState; try { bytesRead = src.EndRead(ar); } catch (IOException _ioex) { src.Close(); dst.Close(); ioex = _ioex; done.Set(); return; } if (bytesRead != 0) { // // Allocate a buffer for the next read, and start write the current // read buffer. // var writeFrom = (byte[])ar.AsyncState; // // Increment the pending writes counter and start writing // the current read block. // Interlocked.Increment(ref pendingWrites); dst.BeginWrite(writeFrom, 0, bytesRead, onWriteCompleted, bytesRead); // // After the write is taking place, start a new read. // We ensure that the read block are written with the proper order. // var readTo = new byte[BUFFER_SIZE]; src.BeginRead(readTo, 0, readTo.Length, onReadCompleted, readTo); } else { // End of source file. src.Close(); // // Decrement the pending writes count and terminate copy if // all writes are done. // if (Interlocked.Decrement(ref pendingWrites) == 0) { // // No writes are pending, close the destination file and // set the *done* event. // dst.Close(); done.Set(); } } }; onWriteCompleted = delegate (IAsyncResult ar) { int bytesWritten = (int)ar.AsyncState; try { dst.EndWrite(ar); fileSize += bytesWritten; } catch (IOException _ioex) { dst.Close(); src.Close(); ioex = _ioex; done.Set(); return; } // // Decrement the pending writes count and terminate copy if // all writes are done. // if (Interlocked.Decrement(ref pendingWrites) == 0) { // // No writes are pending, close the destination file and // set the *done* event. // dst.Close(); done.Set(); } }; // // Start the copy process, issuing the first asynchronous read. // var firstBuf = new byte[BUFFER_SIZE]; src.BeginRead(firstBuf, 0, firstBuf.Length, onReadCompleted, firstBuf); // Wait until completion. done.Wait(); if (ioex != null) { throw ioex; } return fileSize; }
// methods #if !NETSTANDARD1_5 /// <inheritdoc/> public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { ThrowIfDisposed(); return(_stream.BeginRead(buffer, offset, count, callback, state)); }
/// <summary> /// Asynchronously reads data from a stream using BeginRead. /// </summary> /// <param name="stream">The stream on which the method is called</param> /// <param name="buffer">The buffer to read the data into</param> /// <param name="offset">Byte offset in the buffer</param> /// <param name="count">Maximum number of bytes to read</param> /// <returns>Returns non-zero if there are still some data to read</returns> public static Async <int> ReadAsync(this Stream stream, byte[] buffer, int offset, int count) { return(new AsyncPrimitive <int>( (callback, st) => stream.BeginRead(buffer, offset, count, callback, st), stream.EndRead)); }
private Boolean StreamTest(Stream stream, Boolean fSuppress) { if (!fSuppress) { Console.WriteLine("Testing " + stream.GetType() + " for read/write tests"); } String strValue; Int32 iValue; Int32 iLength = 1 << 10; stream.Seek(0, SeekOrigin.Begin); for (int i = 0; i < iLength; i++) { stream.WriteByte((Byte)i); } Byte[] btArr = new Byte[iLength]; for (int i = 0; i < iLength; i++) { btArr[i] = (Byte)i; } stream.Write(btArr, 0, iLength); BinaryWriter bw1 = new BinaryWriter(stream); bw1.Write(false); bw1.Write(true); for (int i = 0; i < 10; i++) { bw1.Write((Byte)i); bw1.Write((SByte)i); bw1.Write((Int16)i); bw1.Write((Char)i); bw1.Write((UInt16)i); bw1.Write(i); bw1.Write((UInt32)i); bw1.Write((Int64)i); bw1.Write((UInt64)i); bw1.Write((Single)i); bw1.Write((Double)i); } Char[] chArr = new Char[iLength]; for (int i = 0; i < iLength; i++) { chArr[i] = (Char)i; } bw1.Write(chArr); bw1.Write(chArr, 512, 512); bw1.Write(new String(chArr)); bw1.Write(new String(chArr)); stream.Seek(0, SeekOrigin.Begin); for (int i = 0; i < iLength; i++) { if (stream.ReadByte() != i % 256) { return(false); } } btArr = new Byte[iLength]; stream.Read(btArr, 0, iLength); for (int i = 0; i < iLength; i++) { if (btArr[i] != (Byte)i) { Console.WriteLine(i + " " + btArr[i] + " " + (Byte)i); return(false); } } BinaryReader br1 = new BinaryReader(stream); if (br1.ReadBoolean()) { return(false); } if (!br1.ReadBoolean()) { return(false); } for (int i = 0; i < 10; i++) { if (br1.ReadByte() != (Byte)i) { return(false); } if (br1.ReadSByte() != (SByte)i) { return(false); } if (br1.ReadInt16() != (Int16)i) { return(false); } if (br1.ReadChar() != (Char)i) { return(false); } if (br1.ReadUInt16() != (UInt16)i) { return(false); } if (br1.ReadInt32() != i) { return(false); } if (br1.ReadUInt32() != (UInt32)i) { return(false); } if (br1.ReadInt64() != (Int64)i) { return(false); } if (br1.ReadUInt64() != (UInt64)i) { return(false); } if (br1.ReadSingle() != (Single)i) { return(false); } if (br1.ReadDouble() != (Double)i) { return(false); } } chArr = br1.ReadChars(iLength); for (int i = 0; i < iLength; i++) { if (chArr[i] != (Char)i) { return(false); } } chArr = new Char[512]; chArr = br1.ReadChars(iLength / 2); for (int i = 0; i < iLength / 2; i++) { if (chArr[i] != (Char)(iLength / 2 + i)) { return(false); } } chArr = new Char[iLength]; for (int i = 0; i < iLength; i++) { chArr[i] = (Char)i; } strValue = br1.ReadString(); if (!strValue.Equals(new String(chArr))) { return(false); } strValue = br1.ReadString(); if (!strValue.Equals(new String(chArr))) { return(false); } try{ stream.Seek(1, SeekOrigin.Current); return(true); }catch (Exception) { } stream.Position = 0; btArr = new Byte[iLength]; for (int i = 0; i < iLength; i++) { btArr[i] = (Byte)(i + 5); } AsyncCallback acb1 = new AsyncCallback(new Co3965StreamMethods().AsyncTestCB); IAsyncResult isync1 = stream.BeginWrite(btArr, 0, btArr.Length, acb1, stream.GetType().ToString()); stream.EndWrite(isync1); stream.Position = 0; for (int i = 0; i < iLength; i++) { if (stream.ReadByte() != (Byte)(i + 5)) { return(false); } } stream.Position = 0; AsyncCallback acb2 = new AsyncCallback(new Co3965StreamMethods().AsyncTestCB); Byte[] btArr1 = new Byte[iLength]; IAsyncResult isync2 = stream.BeginRead(btArr1, 0, btArr1.Length, acb2, stream.GetType().ToString()); iValue = stream.EndRead(isync2); if (iValue != btArr.Length) { return(false); } for (int i = 0; i < iLength; i++) { if (btArr[i] != btArr1[i]) { return(false); } } return(true); }
private void StreamBeginRead() { Stream.BeginRead(ReceiveBuffer, 0, DataBufferSize, BeginReadReceiveCallback, null); }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) { return(m_stream.BeginRead(buffer, offset, size, callback, state)); }
BeginRead(byte [] buffer, int offset, int count, AsyncCallback cback, object state) { return(base_stream.BeginRead(buffer, offset, count, cback, state)); }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { count = GetAllowedCount(count); return(m_innerStream.BeginRead(buffer, offset, count, callback, state)); }
private void onReadInternal(IAsyncResult asyncResult) { _timer.Change(Timeout.Infinite, Timeout.Infinite); var read = -1; try { read = _stream.EndRead(asyncResult); _requestBuffer.Write(_buffer, 0, read); if (_requestBuffer.Length > 32768) { SendError(); Close(true); return; } } catch { if (_requestBuffer != null && _requestBuffer.Length > 0) { SendError(); } if (_socket != null) { closeSocket(); unbind(); } return; } if (read <= 0) { closeSocket(); unbind(); return; } if (processInput(_requestBuffer.GetBuffer())) { if (!_context.HaveError) { _context.Request.FinishInitialization(); } else { SendError(); Close(true); return; } if (!_epListener.BindContext(_context)) { SendError("Invalid host", 400); Close(true); return; } var listener = _context.Listener; if (_lastListener != listener) { removeConnection(); listener.AddConnection(this); _lastListener = listener; } _contextWasBound = true; listener.RegisterContext(_context); return; } _stream.BeginRead(_buffer, 0, _bufferSize, onRead, this); }
internal static void WriteToSync <T>(this Stream stream, Stream toStream, long?copyLength, long?maxLength, ChecksumRequested calculateChecksum, bool syncRead, ExecutionState <T> executionState, StreamDescriptor streamCopyState) { if (copyLength.HasValue && maxLength.HasValue) { throw new ArgumentException(SR.StreamLengthMismatch); } if (stream.CanSeek && maxLength.HasValue && stream.Length - stream.Position > maxLength) { throw new InvalidOperationException(SR.StreamLengthError); } if (stream.CanSeek && copyLength.HasValue && stream.Length - stream.Position < copyLength) { throw new ArgumentOutOfRangeException("copyLength", SR.StreamLengthShortError); } byte[] buffer = new byte[GetBufferSize(stream)]; if (streamCopyState != null && calculateChecksum.HasAny && streamCopyState.ChecksumWrapper == null) { streamCopyState.ChecksumWrapper = new ChecksumWrapper(calculateChecksum.MD5, calculateChecksum.CRC64); } RegisteredWaitHandle waitHandle = null; ManualResetEvent completedEvent = null; if (!syncRead && executionState.OperationExpiryTime.HasValue) { completedEvent = new ManualResetEvent(false); waitHandle = ThreadPool.RegisterWaitForSingleObject( completedEvent, StreamExtensions.MaximumCopyTimeCallback <T>, executionState, executionState.RemainingTimeout, true); } try { long?bytesRemaining = copyLength; int readCount; do { if (executionState.OperationExpiryTime.HasValue && DateTime.Now.CompareTo(executionState.OperationExpiryTime.Value) > 0) { throw Exceptions.GenerateTimeoutException(executionState.Cmd != null ? executionState.Cmd.CurrentResult : null, null); } // Determine how many bytes to read this time so that no more than copyLength bytes are read int bytesToRead = MinBytesToRead(bytesRemaining, buffer.Length); if (bytesToRead == 0) { break; } // Read synchronously or asynchronously readCount = syncRead ? stream.Read(buffer, 0, bytesToRead) : stream.EndRead(stream.BeginRead(buffer, 0, bytesToRead, null /* Callback */, null /* State */)); // Decrement bytes to write from bytes read if (bytesRemaining.HasValue) { bytesRemaining -= readCount; } // Write if (readCount > 0) { toStream.Write(buffer, 0, readCount); // Update the StreamDescriptor after the bytes are successfully committed to the output stream if (streamCopyState != null) { streamCopyState.Length += readCount; if (maxLength.HasValue && streamCopyState.Length > maxLength.Value) { throw new InvalidOperationException(SR.StreamLengthError); } if (streamCopyState.ChecksumWrapper != null) { streamCopyState.ChecksumWrapper.UpdateHash(buffer, 0, readCount); } } } }while (readCount != 0); if (bytesRemaining.HasValue && bytesRemaining != 0) { throw new ArgumentOutOfRangeException("copyLength", SR.StreamLengthShortError); } } catch (Exception) { if (executionState.OperationExpiryTime.HasValue && DateTime.Now.CompareTo(executionState.OperationExpiryTime.Value) > 0) { throw Exceptions.GenerateTimeoutException(executionState.Cmd != null ? executionState.Cmd.CurrentResult : null, null); } else { throw; } } finally { if (waitHandle != null) { waitHandle.Unregister(null); } if (completedEvent != null) { completedEvent.Close(); } } if (streamCopyState != null && streamCopyState.ChecksumWrapper != null) { if (streamCopyState.ChecksumWrapper.CRC64 != null) { streamCopyState.Crc64 = streamCopyState.ChecksumWrapper.CRC64.ComputeHash(); } if (streamCopyState.ChecksumWrapper.MD5 != null) { streamCopyState.Md5 = streamCopyState.ChecksumWrapper.MD5.ComputeHash(); } streamCopyState.ChecksumWrapper = null; } }
private void BeginReading() { try { if (!(_bufferingMode is FrameBuffering)) { _readerSocketStreamBusy.WaitOne(); } var rh = _socketStream.BeginRead(_buffer[_bufNo], 0, _buffer[_bufNo].Length, new AsyncCallback((ar) => { try { int bytesReadCount = _socketStream.EndRead(ar); if (bytesReadCount == 0) { if (_alreadyDisposed.IsTaken()) { ForceComplete(); return; } throw new CassandraConnectionIOException(); } else { foreach (var frame in _bufferingMode.Process(_buffer[_bufNo], bytesReadCount, _socketStream, _compressor)) { Action <ResponseFrame> act = null; if (frame.FrameHeader.StreamId == 0xFF) { act = _frameEventCallback.Value; } else if (frame.FrameHeader.StreamId <= sbyte.MaxValue) { if (_frameReadTimers[frame.FrameHeader.StreamId] != null) { _frameReadTimers[frame.FrameHeader.StreamId].Change(Timeout.Infinite, Timeout.Infinite); } act = _frameReadCallback[frame.FrameHeader.StreamId]; _frameReadCallback[frame.FrameHeader.StreamId] = null; } if (act == null) { throw new InvalidOperationException("Protocol error! Unmached response. Terminating all requests now..."); } act.BeginInvoke(frame, (tar) => { try { (tar.AsyncState as Action <ResponseFrame>).EndInvoke(tar); } catch (Exception ex) { SetupSocketException(ex); } finally { if (!(_bufferingMode is FrameBuffering)) { if (IsHealthy) { BeginReading(); } } } }, act); } _bufNo = 1 - _bufNo; } } catch (Exception ex) { SetupSocketException(ex); } finally { if (_bufferingMode is FrameBuffering) { if (IsHealthy) { BeginReading(); } } else { _readerSocketStreamBusy.Set(); } } }), null); } catch (IOException e) { if (!SetupSocketException(e)) { throw; } } }
protected void TempSave(System.IAsyncResult Res) { if (System.Threading.Monitor.TryEnter(LastManager.StreamLocker)) { try { Stream RadioStream = (Stream)Res.AsyncState; System.Int32 Count = RadioStream.EndRead(Res); if (Count > 0) { this.DeadStreamCount = 0; this.IsKickStarted = false; this.IsRestarted = false; this.TempFile.Write(this.Buffer, 0, Count); this.ReadHandle = RadioStream.BeginRead(this.Buffer, 0, this.Buffer.Length, new System.AsyncCallback(this.TempSave), RadioStream); } else { if (this.DeadStreamCount < 5) { this.DeadStreamCount += 1; this.ReadHandle = RadioStream.BeginRead(this.Buffer, 0, this.Buffer.Length, new System.AsyncCallback(this.TempSave), RadioStream); } else { //TODO: handle a "Not enough content left..." error if (this.IsKickStarted) { if (this.IsRestarted) { //Declare connection dead this.Status = ConnectionStatus.Created; //Give it a handshake, just to try this.Handshake(this.UserID, this.Password); this.IsRestarted = false; this.IsKickStarted = false; } else { RadioStream.Close(); this.TempFile.Close(); this.StartRecording(); this.IsKickStarted = false; this.IsRestarted = true; } } else { this.IsKickStarted = true; this.DeadStreamCount = 0; this.SkipSong(); this.ReadHandle = RadioStream.BeginRead(this.Buffer, 0, this.Buffer.Length, new System.AsyncCallback(this.TempSave), RadioStream); } } } } finally { System.Threading.Monitor.Exit(LastManager.StreamLocker); } } }
/// <summary> /// Ends the async get response. /// </summary> /// <param name="result">The IAsyncResult.</param> /// <exception cref="System.NullReferenceException">GetResponseStream() returned null</exception> private void EndGetResponse(IAsyncResult result) { if (_shutdownToken) { return; } try { _httpWebResponse = (HttpWebResponse)_httpWebRequest.EndGetResponse(result); _httpStream = _httpWebResponse.GetResponseStream(); if (_shutdownToken) { return; } } catch (WebException ex) { OnErrorEvent(new ServerSentErrorEventArgs { Exception = ex }); CloseConnection(); RetryAfterDelay(); } if (_httpWebResponse == null) { return; } var contentType = new ContentType(_httpWebResponse.ContentType); Trace.TraceInformation("EndGetResponse (StatusCode={0}, MediaType={1})", _httpWebResponse.StatusCode, contentType.MediaType); if (_httpWebResponse.StatusCode != HttpStatusCode.OK || contentType.MediaType != "text/event-stream") { // If we get the wrong content type or status code, as per spec, do not attempt to reconnect. OnErrorEvent(new ServerSentErrorEventArgs { Exception = new Exception("Unexpected response from server. Status " + _httpWebResponse.StatusCode + ". Media Type " + contentType.MediaType) }); CloseConnection(); return; } ReadyState = EventSourceState.Open; _retryInterval = DefaultRetryInterval; _eventStream = new StringBuilder(); _eventId = null; _eventType = null; if (_shutdownToken) { return; } if (_httpStream == null) { throw new NullReferenceException("GetResponseStream"); } try { _httpStream.BeginRead(_buffer, 0, _buffer.Length, EndReadFromStream, null); } catch (Exception) { // CloseConnection(); return; } }
/// <summary> /// Start content. /// </summary> /// <exception cref="SocketException">A socket operation failed.</exception> /// <exception cref="IOException">Reading from stream failed.</exception> internal void Start() { Stream = CreateStream(Socket); Stream.BeginRead(_buffer, 0, _buffer.Length, OnReceive, null); }
public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject) { return(_stream.BeginRead(array, offset, numBytes, userCallback, stateObject)); }
/// <summary> /// Start an async read from the socket. Listener.OnRead() is /// eventually called when data arrives. /// </summary> public override void RequestRead() { try { if (m_synch) { lock (this) { if (State != SocketState.Connected) { throw new InvalidOperationException("Socket not connected."); } } while (SyncRead()) { ; } return; } lock (this) { if (m_reading) { throw new InvalidOperationException("Cannot call RequestRead while another read is pending."); } if (State != SocketState.Connected) { throw new InvalidOperationException("Socket not connected."); } m_reading = true; } m_stream.BeginRead(m_buf, 0, m_buf.Length, new AsyncCallback(GotData), null); } catch (AuthenticationException) { Close(); // don't throw. this gets caught elsewhere. } catch (SocketException e) { Close(); // 10053 = An established connection was aborted by the // software in your host machine. // 10054 = An existing connection was forcibly closed // by the remote host. if ((e.ErrorCode != 10053) && (e.ErrorCode != 10054)) { throw; } } catch (IOException) { Close(); } catch (Exception e) { Debug.WriteLine("Exception in RequestRead: " + e.ToString()); Close(); throw e; } }
private void GetNextChunk() { input.BeginRead(buffer, 0, buffer.Length, InputReadComplete, null); }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback?callback, object?state) { return(_requestStream.BeginRead(buffer, offset, count, callback, state)); }
// 读取http返回数据流(回调) private void OnReadCallback(IAsyncResult asyncResult) { Stream responseStream = (Stream)asyncResult.AsyncState; try { int readCount = responseStream.EndRead(asyncResult); if (readCount > 0) { m_CurrentDownloadByte += readCount; // write to file if (m_FileStream == null) { m_FileStream = new FileStream(m_TmpFile, FileMode.Create); } m_FileStream.Write(m_Buffer, 0, readCount); UpdateTimeOut(); // 进度回调 lock (m_Event) { for (int i = m_Event.Count - 1; i >= 0; i--) { if (m_Event[i] == DownloadEvent.Progress) { m_Event.RemoveAt(i); } } m_Event.Add(DownloadEvent.Progress); } // 继续读取 responseStream.BeginRead(m_Buffer, 0, BUFFER_SIZE, new AsyncCallback(OnReadCallback), responseStream); } else // 已经读完 { responseStream.Close(); m_FileStream.Close(); if (File.Exists(m_SaveFile)) { File.Delete(m_SaveFile); } File.Move(m_TmpFile, m_SaveFile); Log.i("Finished!! fileLength:" + m_FileLength + ",Download byte:" + m_CurrentDownloadByte); // 进度回调 lock (m_Event) { m_Event.Clear(); m_Event.Add(DownloadEvent.Finish); } } } catch (Exception exception) { HandleError(exception.Message); } }
/// <summary> /// Async HTTP Read Callback /// IAsyncResult asyncResult (input) -> data necesary to access the webdonwload instance, because /// This is a static method and has not the Webdownload instance /// </summary> private static void AsyncReadCallback(IAsyncResult asyncResult) { WebDownload webDL = (WebDownload)asyncResult.AsyncState; Stream responseStream = webDL.responseStream; try { int read = responseStream.EndRead(asyncResult); if (read > 0) { webDL.ContentStream.Write(webDL.readBuffer, 0, read); webDL.BytesProcessed += read; webDL.OnProgressCallback(webDL.BytesProcessed, webDL.ContentLength); IAsyncResult asynchronousResult = responseStream.BeginRead(webDL.readBuffer, 0, webDL.readBuffer.Length, new AsyncCallback(AsyncReadCallback), webDL); return; } else { if (webDL.BytesProcessed <= 0) { Exception myException = new Exception("400 No tile"); webDL.SaveException(myException); webDL.AsyncFinishDownload(); return; } webDL.SaveException(null); webDL.AsyncFinishDownload(); } } catch (IOException ex) { Utility.Log.Write(Log.Levels.Debug, "NET", "AsyncReadCallback(): IOException: " + ex.Message.ToString() + webDL.BytesProcessed); if (webDL.num_retry > 5) { webDL.SaveException(new Exception("Unable to connect to the remote server several Async Read tries have been broke")); webDL.AsyncFinishDownload(); return; } webDL.num_retry++; webDL.AsyncFinishPrepareRetry(); webDL.DownloadAsync(); } catch (WebException e) { if (webDL.timedOut == false) { // request cancelled. Utility.Log.Write(Log.Levels.Debug, "NET", "AsyncReadCallback(): WebException: " + e.Status.ToString()); webDL.SaveException(e); webDL.AsyncFinishDownload(); //webDL.Cancel(); } } catch (NullReferenceException e) { Utility.Log.Write(Log.Levels.Debug, "NET", "AsyncReadCallback(): NullReferenceException: " + e.Message); webDL.SaveException(e); webDL.AsyncFinishDownload(); } catch (Exception e) { Utility.Log.Write(Log.Levels.Debug, "NET", "AsyncReadCallback(): Exception: " + e.Message); webDL.SaveException(e); //Cancel(); webDL.AsyncFinishDownload(); } }
public static int ReadEx(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellation = default(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 || count > buffer.Length) { throw new ArgumentOutOfRangeException("count"); //Disallow 0 as a debugging aid. } if (offset > buffer.Length - count) { throw new ArgumentOutOfRangeException("count"); } int totalReadCount = 0; while (totalReadCount < count) { cancellation.ThrowIfCancellationRequested(); int currentReadCount; //Big performance problem with BeginRead for other stream types than NetworkStream. //Only take the slow path if cancellation is possible. if (stream is NetworkStream && cancellation.CanBeCanceled) { var ar = stream.BeginRead(buffer, offset + totalReadCount, count - totalReadCount, null, null); if (!ar.CompletedSynchronously) { WaitHandle.WaitAny(new WaitHandle[] { ar.AsyncWaitHandle, cancellation.WaitHandle }, -1); } //EndRead might block, so we need to test cancellation before calling it. //This also is a bug because calling EndRead after BeginRead is contractually required. //A potential fix is to use the ReadAsync API. Another fix is to register a callback with BeginRead that calls EndRead in all cases. cancellation.ThrowIfCancellationRequested(); currentReadCount = stream.EndRead(ar); } else { //IO interruption not supported in this path. currentReadCount = stream.Read(buffer, offset + totalReadCount, count - totalReadCount); } if (currentReadCount == 0) { return(0); } totalReadCount += currentReadCount; } return(totalReadCount); }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => _stream.BeginRead(buffer, offset, count, callback, state);
public static bool AsyncTest(Stream s) { byte[] bigArr = new byte[80000]; byte[] smArr = new byte[128]; int numBytes; AsyncCallback cb; IAsyncResult asyncResult; DateTime startWait; TimeSpan thirtySecs = new TimeSpan(0,0,30); bool firstTime; TimeSpan diff; if(s.GetType( )==typeof(IsolatedStorageFileStream)) { Console.WriteLine("AsyncTest won't run on an IsolatedStorageFileStream " +"since it doesn't support async operations."); return true; } Console.WriteLine(" (08) Async test on "+s.GetType( ).Name); if(s.Position!=0) throw new Exception("AsyncTest assumes stream's position will be 0 when starting."); for(int i=0;i<smArr.Length;i++) smArr[i] = (byte)i; // Try writing something more than 64KB so we have a chance of doing an async write. for(int i=0;i<bigArr.Length;i++) bigArr[i] = (byte)((i%26)+(byte)'A'); // Ensure that we do run our async callback at some point. didAsyncCallbackRun=false; cb = new AsyncCallback(AsyncTestCallback); asyncResult=s.BeginWrite(smArr,0,smArr.Length,cb,String.Empty); /* BeginWrite */ s.EndWrite(asyncResult); /* EndWrite */ if(s.Position!=smArr.Length) throw new Exception("After first BeginWrite call, (s.Position!=smArr.Length) got: " +s.Position); asyncResult=s.BeginWrite(bigArr,0,bigArr.Length,null,String.Empty); s.EndWrite(asyncResult); if(s.Position!=bigArr.Length+smArr.Length) throw new Exception("After second BeginWrite call, s.Position wasn't right! expected: " +(bigArr.Length+smArr.Length)+" got: "+s.Position); // And to be sure things work, test write with an offset. asyncResult=s.BeginWrite(smArr,smArr.Length/2,smArr.Length/2,null,null); /* BeginWrite */ s.EndWrite(asyncResult); /* EndWrite */ if(s.Position!=(smArr.Length/2+bigArr.Length+smArr.Length)) throw new Exception("After third BeginWrite call, s.Position wasn't correct! expected: " +(smArr.Length/2+bigArr.Length+smArr.Length) +" got: "+s.Position); startWait=DateTime.Now; firstTime=true; while(!didAsyncCallbackRun) { if(firstTime) { Console.WriteLine("Waiting for async callback to be run from first BeginWrite call."); firstTime=false; } else Console.Write("."); Thread.Sleep(20); diff=DateTime.Now-startWait; if(diff>thirtySecs) throw new Exception("Async callback didn't run yet after 2 BeginWRITE calls and " +"30 seconds of blocking! " +"This could be a bug in a particular stream class, " +"or an extremely pathetic race condition in this test."); } didAsyncCallbackRun=false; s.Position=0; byte[] input = new byte[(int)s.Length]; // Retest running the async callback here. asyncResult=s.BeginRead(input,0,smArr.Length,cb,String.Empty); /* BeginRead */ numBytes=s.EndRead(asyncResult); /* BeginRead */ if(numBytes!=smArr.Length) throw new Exception("After first BeginRead call, (numBytes!=smArr.Length) got: " +numBytes); if(s.Position!=smArr.Length) throw new Exception("After first BeginRead call, (s.Position!=smArr.Length) got: " +s.Position); asyncResult=s.BeginRead(input,smArr.Length,bigArr.Length,null,String.Empty); /* BeginRead */ numBytes=s.EndRead(asyncResult); /* EndRead */ if(numBytes!=bigArr.Length) throw new Exception("After second BeginRead call, (numBytes!=bigArr.Length) got: " +numBytes); if(s.Position!=bigArr.Length+smArr.Length) throw new Exception("After second BeginRead call, s.Position wasn't right! expected: " +(bigArr.Length+smArr.Length)+" got: "+s.Position); asyncResult=s.BeginRead(input,smArr.Length+bigArr.Length,smArr.Length/2,null,null); /* BeginRead */ numBytes=s.EndRead(asyncResult); /* EndRead */ if(numBytes!=smArr.Length/2) throw new Exception("After third BeginRead call, (numBytes!=smArr.Length/2) got: " +numBytes); if(s.Position!=(smArr.Length/2+bigArr.Length+smArr.Length)) throw new Exception("After third BeginRead call, s.Position wasn't correct! expected: " +(smArr.Length/2+bigArr.Length+smArr.Length) +" got: "+s.Position); for(int i=0;i<smArr.Length;i++) if (smArr[i]!=input[i]) throw new Exception("When reading first smArr copy, position " +i+" was wrong! got: " +input[i]+" expected: "+smArr[i]); int offset = smArr.Length; for(int i=0;i<bigArr.Length;i++) if (bigArr[i]!=input[i+offset]) throw new Exception("When reading bigArr copy, position " +(i+offset)+" was wrong! i: "+i+" got: " +input[i+offset]+" expected: "+bigArr[i]); offset=smArr.Length+bigArr.Length; for(int i=0;i<smArr.Length/2;i++) if (smArr[i+smArr.Length/2]!=input[i+offset]) throw new Exception("When reading second smArr copy, position " +(i+offset)+" was wrong! i: "+i+" got: " +input[i+offset]+" expected: " +smArr[i+smArr.Length/2]); startWait=DateTime.Now; firstTime=true; while(!didAsyncCallbackRun) { if (firstTime) { Console.WriteLine("Waiting for async callback to be run from " +"first BeginRead call."); firstTime=false; } else Console.Write("."); Thread.Sleep(20); diff=DateTime.Now-startWait; if(diff>thirtySecs) throw new Exception("Async callback didn't run yet after 2 BeginREAD " +"calls and 30 seconds of blocking! " +"This could be a bug in a particular stream " +"class, or an extremely pathetic race " +"condition in this test."); } didAsyncCallbackRun=false; return true; }
private Boolean StreamTest(Stream stream, Boolean fSuppress){ if(!fSuppress) Console.WriteLine("Testing " + stream.GetType() + " for read/write tests"); String strValue; Int32 iValue; Int32 iLength = 1 << 10; stream.Seek(0, SeekOrigin.Begin); for(int i=0; i<iLength; i++) stream.WriteByte((Byte)i); Byte[] btArr = new Byte[iLength]; for(int i=0; i<iLength; i++) btArr[i] = (Byte)i; stream.Write(btArr, 0, iLength); BinaryWriter bw1 = new BinaryWriter(stream); bw1.Write(false); bw1.Write(true); for(int i=0; i<10; i++){ bw1.Write((Byte)i); bw1.Write((SByte)i); bw1.Write((Int16)i); bw1.Write((Char)i); bw1.Write((UInt16)i); bw1.Write(i); bw1.Write((UInt32)i); bw1.Write((Int64)i); bw1.Write((UInt64)i); bw1.Write((Single)i); bw1.Write((Double)i); } Char[] chArr = new Char[iLength]; for(int i=0; i<iLength;i++) chArr[i] = (Char)i; bw1.Write(chArr); bw1.Write(chArr, 512, 512); bw1.Write(new String(chArr)); bw1.Write(new String(chArr)); stream.Seek(0, SeekOrigin.Begin); for(int i=0; i<iLength; i++){ if(stream.ReadByte() != i%256){ return false; } } btArr = new Byte[iLength]; stream.Read(btArr, 0, iLength); for(int i=0; i<iLength; i++){ if(btArr[i] != (Byte)i){ Console.WriteLine(i + " " + btArr[i] + " " + (Byte)i); return false; } } BinaryReader br1 = new BinaryReader(stream); if(br1.ReadBoolean()) return false; if(!br1.ReadBoolean()) return false; for(int i=0; i<10; i++){ if(br1.ReadByte() != (Byte)i) return false; if(br1.ReadSByte() != (SByte)i) return false; if(br1.ReadInt16() != (Int16)i) return false; if(br1.ReadChar() != (Char)i) return false; if(br1.ReadUInt16() != (UInt16)i) return false; if(br1.ReadInt32() != i) return false; if(br1.ReadUInt32() != (UInt32)i) return false; if(br1.ReadInt64() != (Int64)i) return false; if(br1.ReadUInt64() != (UInt64)i) return false; if(br1.ReadSingle() != (Single)i) return false; if(br1.ReadDouble() != (Double)i) return false; } chArr = br1.ReadChars(iLength); for(int i=0; i<iLength;i++){ if(chArr[i] != (Char)i) return false; } chArr = new Char[512]; chArr = br1.ReadChars(iLength/2); for(int i=0; i<iLength/2;i++){ if(chArr[i] != (Char)(iLength/2+i)) return false; } chArr = new Char[iLength]; for(int i=0; i<iLength;i++) chArr[i] = (Char)i; strValue = br1.ReadString(); if(!strValue.Equals(new String(chArr))) return false; strValue = br1.ReadString(); if(!strValue.Equals(new String(chArr))){ return false; } try{ stream.Seek(1, SeekOrigin.Current); return true; }catch(Exception){ } stream.Position = 0; btArr = new Byte[iLength]; for(int i=0; i<iLength; i++) btArr[i] = (Byte)(i + 5); AsyncCallback acb1 = new AsyncCallback(new Co3965StreamMethods().AsyncTestCB); IAsyncResult isync1 = stream.BeginWrite(btArr, 0, btArr.Length, acb1, stream.GetType().ToString()); stream.EndWrite(isync1); stream.Position = 0; for(int i=0; i<iLength; i++){ if(stream.ReadByte() != (Byte)(i+5)) return false; } stream.Position = 0; AsyncCallback acb2 = new AsyncCallback(new Co3965StreamMethods().AsyncTestCB); Byte[] btArr1 = new Byte[iLength]; IAsyncResult isync2 = stream.BeginRead(btArr1, 0, btArr1.Length, acb2, stream.GetType().ToString()); iValue = stream.EndRead(isync2); if(iValue!=btArr.Length) return false; for(int i=0; i<iLength; i++){ if(btArr[i] != btArr1[i]) return false; } return true; }
public static bool SetLengthTest(Stream s) { Console.WriteLine(" (10) SetLengthTest on "+s.GetType( ).Name); if(!s.CanSeek) { Console.WriteLine("SetLengthTest shouldn't run on non-seekable stream "+s.GetType( ).Name); try { s.SetLength(0); throw new Exception("SetLength to 0 on a non-seekable stream should have failed!"); } catch(NotSupportedException) { } return true; } if(!s.CanWrite) { Console.WriteLine("SetLengthTest shouldn't run on non-writable stream "+s.GetType( ).Name); try { s.SetLength(0); throw new Exception("SetLength to 0 on a non-writable stream should have failed! " +"s.Length: "+s.Length); } catch(NotSupportedException) { } return true; } s.SetLength(0); if(s.Length!=0) throw new Exception("SetLength to 0, but Length is: "+s.Length); if(s.Position!=0) throw new Exception("Set length to 0. Position should be zero too: "+s.Position); s.SetLength(10); if(s.Length!=10) throw new Exception("SetLength to 10, but Length is: "+s.Length); if(s.Position!=0) throw new Exception("Set length to 10, yet Position should be zero still: "+s.Position); if(s.CanRead) { byte[] bytes = new byte[500]; IAsyncResult asyncResult = s.BeginRead(bytes,0,500,null,null); int numBytes = s.EndRead(asyncResult); if(numBytes!=10) throw new Exception("Number of bytes got back from EndRead was wrong! " +"should have been 10, but got: "+numBytes); if(s.Position!=10) throw new Exception("After async read, position should be 10, but was: "+s.Position); } return true; }
public static bool CanPropertiesTest(Stream s) { Console.WriteLine(" (06) Can-Properties Test on "+s.GetType( ).Name); byte[] bytes = new byte[1]; int bytesTransferred; IAsyncResult asyncResult; if(s.CanRead) { // Ensure all Read methods work, if CanRead is true. int n = s.ReadByte( ); if(n==-1) throw new Exception("On a readable stream, ReadByte returned -1..."); bytesTransferred=s.Read(bytes,0,1); if(bytesTransferred!=1) throw new Exception("Read(byte[],0,1) should have returned 1! got: "+bytesTransferred); asyncResult=s.BeginRead(bytes,0,1,null,null); /* BeginRead */ bytesTransferred=s.EndRead(asyncResult); /* EndRead */ if(bytesTransferred!=1) throw new Exception("BeginRead(byte[],0,1) should have returned 1! got: " +bytesTransferred); } // End of (s.CanRead) Block else { // Begin of (!s.CanRead) Block try { s.ReadByte( ); throw new Exception("ReadByte on an unreadable stream should have thrown!"); } catch(NotSupportedException) { } try { s.Read(bytes,0,1); throw new Exception("Read(bytes,0,1) on an unreadable stream should have thrown!"); } catch(NotSupportedException) { } try { s.BeginRead(bytes,0,1,null,null); /* BeginRead */ throw new Exception("BeginRead on an unreadable stream should have thrown!"); } catch(NotSupportedException) { } } // End of (!s.CanRead) Block if(s.CanWrite) { // Ensure write methods work if CanWrite returns true. s.WriteByte(0); s.Write(bytes,0,1); asyncResult = s.BeginWrite(bytes,0,1,null,null); /* BeginWrite */ s.EndWrite(asyncResult); /* EndWrite */ } // End of (s.CanWrite) Block else { // Begin of (!s.CanWrite) Block try { s.WriteByte(2); throw new Exception("WriteByte on an unreadable stream should have thrown!"); } catch(NotSupportedException) { } try { s.Write(bytes,0,1); throw new Exception("Write(bytes,0,1) on an unreadable stream should have thrown!"); } catch(NotSupportedException) { } try { s.BeginWrite(bytes,0,1,null,null); /* BeginWrite */ throw new Exception("BeginWrite on an unreadable stream should have thrown!"); } catch(NotSupportedException) { } } // End of (!s.CanWrite) Block if(s.CanSeek) { // Ensure length-related methods work if CanSeek returns true long n = s.Length; n=s.Position; if(s.Position>s.Length) throw new Exception("Position is beyond the length of the stream!"); s.Position=0; s.Position=s.Length; if(s.Position!=s.Seek(0,SeekOrigin.Current)) throw new Exception("s.Position!=s.Seek(0,SeekOrigin.Current)"); if(s.CanWrite) // Verify you can set the length, if it's writable. s.SetLength(s.Length); } // End of (s.CanSeek) Block else { // Begin of (!s.CanSeek) Block try { s.Position=5; throw new Exception("set_Position should throw on a non-seekable stream!"); } catch(NotSupportedException) { } try { long n = s.Position; throw new Exception("get_Position should throw on a non-seekable stream!"); } catch(NotSupportedException) { } try { long n = s.Length; throw new Exception("get_Length should throw on a non-seekable stream!"); } catch(NotSupportedException) { } try { s.SetLength(1); throw new Exception("SetLength should throw on a non-seekable stream!"); } catch(NotSupportedException) { } try { s.Seek(0,SeekOrigin.Current); throw new Exception("Seek should throw on a non-seekable stream!"); } catch(NotSupportedException) { } } // End of (!s.CanSeek) Block return true; }
private void AcceptCompleted(IAsyncResult ar) { // Connect to this client m_client = m_server.EndAcceptTcpClient(ar); // Accept another client new ClientConnectionApm(m_server); // Start processing this client m_stream = m_client.GetStream(); // Read 1 byte from client which contains length of additional data m_stream.BeginRead(m_inputData, 0, 1, ReadLengthCompleted, null); }
public static bool ErrorTest(Stream s) { Console.WriteLine(" (09) Error test on stream: "+s.GetType( ).Name); // Test EndRead & EndWrite's Type safety byte[] bytes = new byte[0]; IAsyncResult asyncResult; BogusIAsyncResult bogus = new BogusIAsyncResult( ); if(s.CanRead) { asyncResult = s.BeginRead(bytes,0,0,null,null); /* BeginRead */ try { s.EndWrite(asyncResult); /* EndWrite */ throw new Exception("EndWrite with an asyncResult from BeginRead should have thrown!"); } catch(ArgumentException) { } } if(s.CanWrite) { asyncResult=s.BeginWrite(bytes,0,0,null,null); /* BeginWrite */ try { s.EndRead(asyncResult); /* EndRead */ throw new Exception("EndRead with an asyncResult from BeginWrite should have thrown!"); } catch(ArgumentException) { } // Verify EndWrite doesn't allow using the same asyncResult twice. s.EndWrite(asyncResult); /* EndWrite */ try { s.EndWrite(asyncResult); /* EndWrite */ throw new Exception("Exception EndWrite was called twice w/ same IAsyncResult from " +s.GetType( ).Name+", but didn't throw!"); } catch(InvalidOperationException) { } } try { s.EndRead(bogus); /* EndRead */ throw new Exception("EndRead with a bogus IAsyncResult object should have thrown!"); } catch(ArgumentException) { } try { s.EndWrite(bogus); /* EndWrite */ throw new Exception("EndWrite with a bogus IAsyncResult object should have thrown!"); } catch(ArgumentException) { } return true; }
private static void readCallback(IAsyncResult asynchronousResult) { NetWebClient netWebClient = asynchronousResult.AsyncState as NetWebClient; try { Stream stream = netWebClient.responseStream_; int num = stream.EndRead(asynchronousResult); if (0 < num) { NetWebClient.shared_.memoryStream_.Write(NetWebClient.shared_.buffer_, 0, num); stream.BeginRead(NetWebClient.shared_.buffer_, 0, 1024, new AsyncCallback(NetWebClient.readCallback), netWebClient); } else if (asynchronousResult.IsCompleted) { byte[] buffer_ = NetWebClient.shared_.buffer_; NetWebClient.shared_.memoryStream_.Position = 0L; if (0 < netWebClient.encryptVersion_) { if (NetWebClient.descryptTo(NetWebClient.shared_.compressedStream_, NetWebClient.shared_.memoryStream_) < 0) { throw new Exception("A message may be corrupted."); } NetWebClient.swap <MemoryStream>(ref NetWebClient.shared_.memoryStream_, ref NetWebClient.shared_.compressedStream_); } NetWebClient.Encoding encoding = netWebClient.encoding_; if (encoding != NetWebClient.Encoding.Deflate) { if (encoding == NetWebClient.Encoding.GZip) { NetWebClient.swap <MemoryStream>(ref NetWebClient.shared_.memoryStream_, ref NetWebClient.shared_.compressedStream_); using (GZipStream gzipStream = new GZipStream(NetWebClient.shared_.compressedStream_, CompressionMode.Decompress, true)) { NetWebClient.copyTo(NetWebClient.shared_.memoryStream_, gzipStream, buffer_, 1024); } } } else { NetWebClient.swap <MemoryStream>(ref NetWebClient.shared_.memoryStream_, ref NetWebClient.shared_.compressedStream_); MemoryStream memoryStream_ = NetWebClient.shared_.memoryStream_; MemoryStream compressedStream_ = NetWebClient.shared_.compressedStream_; compressedStream_.ReadByte(); compressedStream_.ReadByte(); using (DeflateStream deflateStream = new DeflateStream(compressedStream_, CompressionMode.Decompress, true)) { NetWebClient.copyTo(memoryStream_, deflateStream, buffer_, 1024); } if (!NetWebClient.checkHash(compressedStream_, memoryStream_)) { netWebClient.setError(WebExceptionStatus.UnknownError, "Invalid Hash", 5, null); return; } } netWebClient.setSuccess(4); } } catch (WebException ex) { netWebClient.setError(ex.Status, ex.Message, 5, ex.Response as HttpWebResponse); } catch (Exception ex2) { netWebClient.setError(WebExceptionStatus.UnknownError, ex2.Message, 5, null); } }
protected void SaveSong(MetaInfo SongInfo) { System.Boolean DownloadCovers = false; System.String AlbumPath = ""; System.String NewFilePath = ""; lock (LastManager.StreamLocker) { Stream RadioStream = (Stream)this.ReadHandle.AsyncState; System.Int32 Count = RadioStream.EndRead(this.ReadHandle); if (this.SkipSave || !SongInfo.Streaming) { //Close file this.TempFile.Close(); //Create or overwrite tempfile this.TempFile = File.Create(PathSettings.TempFilePath); //Start recording agian this.ReadHandle = RadioStream.BeginRead(this.Buffer, 0, this.Buffer.Length, new System.AsyncCallback(this.TempSave), RadioStream); //Change SkipSave this.SkipSave = false; } else { //Write last data from stream this.TempFile.Write(this.Buffer, 0, Count); //Write metadata to stream as ID3v1 SongInfo.AppendID3(this.TempFile); //Write the file, and close it this.TempFile.Flush(); this.TempFile.Close(); this.TempFile.Dispose(); //Filesystem paths AlbumPath = this.MusicPath + System.IO.Path.DirectorySeparatorChar + LastManager.RemoveIllegalChars(SongInfo.Artist) + System.IO.Path.DirectorySeparatorChar + LastManager.RemoveIllegalChars(SongInfo.Album) + System.IO.Path.DirectorySeparatorChar; NewFilePath = AlbumPath + LastManager.RemoveIllegalChars(SongInfo.Track) + ".mp3"; //Dont overwrite file if it already exist, new rip may be bad, and we should leave it to the user to sort them manually if (File.Exists(NewFilePath)) { File.Delete(PathSettings.TempFilePath); } else { if (!Directory.Exists(AlbumPath)) { Directory.CreateDirectory(AlbumPath); } File.Move(PathSettings.TempFilePath, NewFilePath); } //Create or overwrite tempfile this.TempFile = File.Create(PathSettings.TempFilePath); //Start recording agian this.ReadHandle = RadioStream.BeginRead(this.Buffer, 0, this.Buffer.Length, new System.AsyncCallback(this.TempSave), RadioStream); //Set download covers, do this outside the lock. DownloadCovers = true; } } if (DownloadCovers) { //Download covers WebClient Client = new WebClient(); if ((!File.Exists(AlbumPath + "SmallCover.jpg")) && SongInfo.AlbumcoverSmall != null) { Client.DownloadFile(SongInfo.AlbumcoverSmall, AlbumPath + "SmallCover.jpg"); } if ((!File.Exists(AlbumPath + "MediumCover.jpg")) && SongInfo.AlbumcoverMedium != null) { Client.DownloadFile(SongInfo.AlbumcoverMedium, AlbumPath + "MediumCover.jpg"); } if ((!File.Exists(AlbumPath + "LargeCover.jpg")) && SongInfo.AlbumcoverLarge != null) { Client.DownloadFile(SongInfo.AlbumcoverLarge, AlbumPath + "LargeCover.jpg"); } } }
// // File copy using APM asynchronous read and synchronous write operations. // static long ApmFileCopy(Stream src, Stream dst) { var done = new ManualResetEventSlim(false); long fileSize = 0; IOException ioex = null; AsyncCallback onReadCompleted = null; onReadCompleted = delegate(IAsyncResult iar) { int bytesRead = 0; try { bytesRead = src.EndRead(iar); } catch (IOException _ioex) { src.Close(); dst.Close(); ioex = _ioex; done.Set(); return; } if (bytesRead != 0) { // // The read buffer is passed through IasyncResult.AsyncState. // Allocate a new buffer for the next read and issue an synchronous write. // // The lock ensures that we can't process the completion of the new read // completion before terminate the current write. // var writeFrom = (byte[])iar.AsyncState; var readTo = new byte[BUFFER_SIZE]; lock(dst) { src.BeginRead(readTo, 0, readTo.Length, onReadCompleted, readTo); dst.Write(writeFrom, 0, bytesRead); fileSize += bytesRead; } } else { // // We reach the EOF on the source stream. // We must ensure that the write of the last block is done, // before close the destination stream and set the event. // src.Close(); lock(dst) {} dst.Close(); done.Set(); return; } }; // // Start the copy process, issuingthe first asynchronous read. // var firstBuf = new byte[BUFFER_SIZE]; src.BeginRead(firstBuf, 0, firstBuf.Length, onReadCompleted, firstBuf); // Wait until completion. done.Wait(); if (ioex != null) { throw ioex; } return fileSize; }