public void Test_UniteStream() { using (MemoryStream memoryStream1 = new MemoryStream(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 })) using (MemoryStream memoryStream2 = new MemoryStream(new byte[] { 8, 9, 10, 11, 12, 13, 14 })) { using (UniteStream addStream = new UniteStream(new RangeStream(memoryStream1, 2, 4), new RangeStream(memoryStream2, 2, 4))) { byte[] buffer1 = new byte[2]; addStream.Read(buffer1, 0, buffer1.Length); Assert.IsTrue(CollectionUtilities.Equals(new byte[] { 2, 3 }, buffer1), "UniteStream #1"); byte[] buffer2 = new byte[2]; addStream.Read(buffer2, 0, buffer2.Length); Assert.IsTrue(CollectionUtilities.Equals(new byte[] { 4, 5 }, buffer2), "UniteStream #2"); byte[] buffer3 = new byte[2]; addStream.Read(buffer3, 0, buffer3.Length); Assert.IsTrue(CollectionUtilities.Equals(new byte[] { 10, 11 }, buffer3), "UniteStream #3"); byte[] buffer4 = new byte[2]; addStream.Read(buffer4, 0, buffer4.Length); Assert.IsTrue(CollectionUtilities.Equals(new byte[] { 12, 13 }, buffer4), "UniteStream #4"); } } }
public override void Send(Stream stream, TimeSpan timeout, Information options) { if (_disposed) { throw new ObjectDisposedException(this.GetType().FullName); } if (!_connect) { throw new ConnectionException(); } if (stream == null) { throw new ArgumentNullException("stream"); } if (stream.Length == 0) { throw new ArgumentOutOfRangeException("stream"); } lock (_sendLock) { using (RangeStream targetStream = new RangeStream(stream, stream.Position, stream.Length - stream.Position, true)) { try { _sendStopwatch.Restart(); Stream headerStream = new BufferStream(_bufferManager); headerStream.Write(NetworkConverter.GetBytes((int)targetStream.Length), 0, 4); byte[] sendBuffer = null; try { sendBuffer = _bufferManager.TakeBuffer(1024 * 4); using (Stream dataStream = new UniteStream(headerStream, new WrapperStream(targetStream, true))) { for (; ;) { int sendLength = (int)Math.Min(dataStream.Length - dataStream.Position, sendBuffer.Length); if (sendLength == 0) { break; } if (_bandwidthLimit != null) { sendLength = _bandwidthLimit.GetOutBandwidth(this, sendLength); if (sendLength < 0) { throw new ConnectionException(); } } dataStream.Read(sendBuffer, 0, sendLength); var time = BaseConnection.CheckTimeout(_sendStopwatch.Elapsed, timeout); time = (time < _sendTimeSpan) ? time : _sendTimeSpan; _cap.Send(sendBuffer, 0, sendLength, time); _aliveStopwatch.Restart(); _sentByteCount.Add(sendLength); } } } finally { _bufferManager.ReturnBuffer(sendBuffer); } _aliveTimer.Change(1000 * 30); } catch (ConnectionException e) { throw e; } catch (Exception e) { throw new ConnectionException(e.Message, e); } } } }