public void TestBasicBuffering() { DummySession sess = new DummySession(); sess.FilterChain.AddFirst("peer", new DummyFilter()); sess.FilterChain.AddFirst("logger", new LoggingFilter()); BufferedWriteFilter bFilter = new BufferedWriteFilter(10); sess.FilterChain.AddLast("buffer", bFilter); IoBuffer data = IoBuffer.Allocate(1); for (byte i = 0; i < 20; i++) { data.Put((byte)(0x30 + i)); data.Flip(); sess.Write(data); data.Clear(); } // Add one more byte to overflow the final buffer data.Put((byte)0); data.Flip(); sess.Write(data); // Flush the final byte bFilter.Flush(sess); sess.Close(true); }
public IDecodingState Decode(IoBuffer input, IProtocolDecoderOutput output) { Int32 terminatorPos = input.IndexOf(_terminator); if (terminatorPos >= 0) { Int32 limit = input.Limit; IoBuffer product; if (input.Position < terminatorPos) { input.Limit = terminatorPos; if (_buffer == null) { product = input.Slice(); } else { _buffer.Put(input); product = _buffer.Flip(); _buffer = null; } input.Limit = limit; } else { // When input contained only terminator rather than actual data... if (_buffer == null) { product = IoBuffer.Allocate(0); } else { product = _buffer.Flip(); _buffer = null; } } input.Position = terminatorPos + 1; return(FinishDecode(product, output)); } if (_buffer == null) { _buffer = IoBuffer.Allocate(input.Remaining); _buffer.AutoExpand = true; } _buffer.Put(input); return(this); }
/// <summary> /// Processes receive events. /// </summary> /// <param name="e"></param> public void ProcessReceive(SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { if (e.BytesTransferred > 0) { _readBuffer.Position = e.BytesTransferred; _readBuffer.Flip(); if (ReuseBuffer) { EndReceive(_readBuffer); } else { IoBuffer buf = IoBuffer.Allocate(_readBuffer.Remaining); buf.Put(_readBuffer); buf.Flip(); EndReceive(buf); } return; } else { // closed //Processor.Remove(this); this.FilterChain.FireInputClosed(); } } else { EndReceive(new SocketException((Int32)e.SocketError)); } }
public IDecodingState Decode(IoBuffer input, IProtocolDecoderOutput output) { if (_buffer == null) { if (input.Remaining >= _length) { Int32 limit = input.Limit; input.Limit = input.Position + _length; IoBuffer product = input.Slice(); input.Position = input.Position + _length; input.Limit = limit; return(FinishDecode(product, output)); } _buffer = IoBuffer.Allocate(_length); _buffer.Put(input); return(this); } if (input.Remaining >= _length - _buffer.Position) { Int32 limit = input.Limit; input.Limit = input.Position + _length - _buffer.Position; _buffer.Put(input); input.Limit = limit; IoBuffer product = _buffer; _buffer = null; return(FinishDecode(product.Flip(), output)); } _buffer.Put(input); return(this); }
/// <summary> /// Processes receive events. /// </summary> /// <param name="e"></param> public void ProcessReceive(SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { if (e.BytesTransferred > 0) { _readBuffer.Position = e.BytesTransferred; _readBuffer.Flip(); if (ReuseBuffer) { EndReceive(_readBuffer); } else { IoBuffer buf = IoBuffer.Allocate(_readBuffer.Remaining); buf.Put(_readBuffer); buf.Flip(); EndReceive(buf); } return; } } else if (e.SocketError != SocketError.OperationAborted && e.SocketError != SocketError.Interrupted) { EndReceive(new SocketException((Int32)e.SocketError)); } }
/// <inheritdoc/> public override void Encode(IoSession session, Object message, IProtocolEncoderOutput output) { if (!message.GetType().IsSerializable) { throw new System.Runtime.Serialization.SerializationException(message.GetType() + " is not serializable."); } IoBuffer buf = IoBuffer.Allocate(64); buf.AutoExpand = true; buf.PutInt32(0); buf.PutObject(message); Int32 objectSize = buf.Position - 4; if (objectSize > _maxObjectSize) { throw new ArgumentException(String.Format("The encoded object is too big: {0} (> {1})", objectSize, _maxObjectSize), "message"); } buf.PutInt32(0, objectSize); buf.Flip(); output.Write(buf); }
private IoBuffer ReadBuffer() { IoBuffer buf = IoBuffer.Allocate(_sessionStream.Remaining); while (true) { ArraySegment <Byte> array = buf.GetRemaining(); Int32 bytesRead = _sslStream.Read(array.Array, array.Offset, array.Count); if (bytesRead <= 0) { break; } buf.Position += bytesRead; if (_sessionStream.Remaining == 0) { break; } else { // We have to grow the target buffer, it's too small. buf.Capacity <<= 1; buf.Limit = buf.Capacity; } } buf.Flip(); return(buf); }
public void SendMsg() { //lock (this) { while (m_sendMsgs.Count > 0) { MessageBody msg = m_sendMsgs.Dequeue(); if (msg != null) { m_sendBuffer.Clear(); Array.Clear(m_sendData, 0, m_sendData.Length); int len = CPacket.HEADER_TYPE_BYTES + msg.data.Length; m_sendBuffer.PutInt32(len); m_sendBuffer.PutInt16((short)msg.type); m_sendBuffer.Put(msg.data); m_sendBuffer.Flip(); m_sendBuffer.Get(m_sendData, 0, len + CPacket.HEADER_LENGTH_BYTES); m_currentSendBufferWritePosition = len + CPacket.HEADER_LENGTH_BYTES; SendMsg(m_sendData); } } } }
/// <inheritdoc/> public void MergeAll() { if (!_buffersOnly) { throw new InvalidOperationException("The encoded messages contains a non-buffer."); } if (_queue.Count < 2) { // no need to merge! return; } Int32 sum = 0; foreach (var item in _queue) { sum += ((IoBuffer)item).Remaining; } IoBuffer newBuf = IoBuffer.Allocate(sum); for (; ;) { Object obj = _queue.Dequeue(); if (obj == null) { break; } newBuf.Put((IoBuffer)obj); } newBuf.Flip(); _queue.Enqueue(newBuf); }
public void GetMsg(object o) { while (m_isSocketReady) { int recieveLen = 0; try { if (m_mySocket.Available > 0) { recieveLen = m_mySocket.Client.Receive(m_getData, 0, (int)m_mySocket.ReceiveBufferSize, SocketFlags.None); } else { System.Threading.Thread.Sleep(1); break; } } catch (Exception e) { DEBUG.Error(e.Message); break; } m_readBuffer.Put(m_getData, 0, recieveLen); Array.Clear(m_getData, 0, m_getData.Length); m_readBuffer.Flip(); int len = GetPacketLength(m_readBuffer); if (len < 0) { break; } MessageBody msg = new MessageBody(); msg.size = (uint)CPacket.PopPacketLength(m_readBuffer); msg.type = (ushort)CPacket.PopPacketType(m_readBuffer); byte[] data = new byte[len - CPacket.HEADER_TYPE_BYTES]; m_readBuffer.Get(data, 0, len - CPacket.HEADER_TYPE_BYTES); msg.data = data; m_recievedMsgs.Add(msg); bool isFinish = false; if (m_readBuffer.HasRemaining) { m_readBuffer.Compact(); } else { m_readBuffer.Clear(); isFinish = true; } if (isFinish) { break; } } }
public override void WriteByte(Byte value) { IoBuffer buf = IoBuffer.Allocate(1); buf.Put(value); buf.Flip(); _sslHandler.WriteBuffer(buf); }
private void ReceiveCallback(IAsyncResult ar) { System.Net.Sockets.Socket socket = (System.Net.Sockets.Socket)ar.AsyncState; Int32 read = 0; try { read = socket.EndReceive(ar); } catch (ObjectDisposedException) { // do nothing return; } catch (SocketException ex) { if (ex.SocketErrorCode != SocketError.OperationAborted && ex.SocketErrorCode != SocketError.Interrupted && ex.SocketErrorCode != SocketError.ConnectionReset) { EndReceive(ex); } else { // closed Processor.Remove(this); } return; } catch (Exception ex) { EndReceive(ex); return; } if (read > 0) { if (ReuseBuffer) { EndReceive(IoBuffer.Wrap(_readBuffer, 0, read)); } else { IoBuffer buf = IoBuffer.Allocate(read); buf.Put(_readBuffer, 0, read); buf.Flip(); EndReceive(buf); } } else { // closed //Processor.Remove(this); this.FilterChain.FireInputClosed(); } }
public void Encode(IoSession session, PacketOutStream message, IProtocolEncoderOutput output) { int size = message.GetSize(); IoBuffer buf = IoBuffer.Allocate(size + 4); buf.PutInt32(size); buf.Put(message.getPackets2()); buf.Flip(); output.Write(buf); }
/// <inheritdoc/> protected override IoBuffer GetNextBuffer(IFileRegion fileRegion) { if (fileRegion.RemainingBytes <= 0L) { return(null); } Int32 bufferSize = (Int32)Math.Min(WriteBufferSize, fileRegion.RemainingBytes); IoBuffer buffer = IoBuffer.Allocate(bufferSize); fileRegion.Read(buffer); buffer.Flip(); return(buffer); }
/// <inheritdoc/> public override void Encode(IoSession session, Object message, IProtocolEncoderOutput output) { String value = (String)message; IoBuffer buffer = IoBuffer.Allocate(value.Length); buffer.AutoExpand = true; buffer.PutPrefixedString(value, PrefixLength, Encoding); if (buffer.Position > MaxDataLength) { throw new ArgumentException("Data length: " + buffer.Position); } buffer.Flip(); output.Write(buffer); }
public void SetUp() { acceptor.MessageReceived += (s, e) => { // Just echo the received bytes. IoBuffer rb = (IoBuffer)e.Message; IoBuffer wb = IoBuffer.Allocate(rb.Remaining); wb.Put(rb); wb.Flip(); e.Session.Write(wb); }; acceptor.Bind(CreateServerEndPoint(0)); port = GetPort(acceptor.LocalEndPoint); }
public bool Send(IoBuffer output) { try { output.Flip(); var buffer = output.GetRemainingArray(); Client.Client.Send(buffer); } catch (Exception) { return(false); } if (handler != null) { return(handler.Await()); } return(true); }
private void ProcessReceive(SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { IoBuffer buf = IoBuffer.Allocate(e.BytesTransferred); buf.Put(e.Buffer, e.Offset, e.BytesTransferred); buf.Flip(); EndReceive((SocketContext)e.UserToken, buf, e.RemoteEndPoint); } else if (e.SocketError != SocketError.OperationAborted && e.SocketError != SocketError.Interrupted) { ExceptionMonitor.Instance.ExceptionCaught(new SocketException((Int32)e.SocketError)); } }
public void Encode(IoSession session, T message, IProtocolEncoderOutput output) { IoBuffer buf = IoBuffer.Allocate(16); buf.AutoExpand = true; // Enable auto-expand for easier encoding // Encode a header buf.PutInt16((short)_type); buf.PutInt32(message.Sequence); // Encode a body EncodeBody(session, message, buf); buf.Flip(); output.Write(buf); }
public IDecodingState FinishDecode(IProtocolDecoderOutput output) { IoBuffer readData; if (_buffer == null) { readData = IoBuffer.Allocate(0); } else { readData = _buffer.Flip(); _buffer = null; } return(FinishDecode(readData, output)); }
public override void MessageReceived(IoSession session, Object message) { IoBuffer rb = message as IoBuffer; if (rb == null) { return; } // Write the received data back to remote peer IoBuffer wb = IoBuffer.Allocate(rb.Remaining); wb.Put(rb); wb.Flip(); session.Write(wb); }
private void InternalFlush(INextFilter nextFilter, IoSession session, IoBuffer buf) { IoBuffer tmp = null; lock (buf) { buf.Flip(); tmp = buf.Duplicate(); buf.Clear(); } if (log.IsDebugEnabled) { log.Debug("Flushing buffer: " + tmp); } nextFilter.FilterWrite(session, new DefaultWriteRequest(tmp)); }
public IDecodingState FinishDecode(IProtocolDecoderOutput output) { try { if (_buffer == null) { _buffer = IoBuffer.Allocate(0); } _buffer.Flip(); return(FinishDecode(_buffer, output)); } finally { _buffer = null; } }
private Object GetMessageCopy(Object message) { Object messageCopy = message; IoBuffer rb = message as IoBuffer; if (rb != null) { rb.Mark(); IoBuffer wb = IoBuffer.Allocate(rb.Remaining); wb.Put(rb); wb.Flip(); rb.Reset(); messageCopy = wb; } return(messageCopy); }
private static FileInfo CreateLargeFile() { IoBuffer buffer = IoBuffer.Allocate(FILE_SIZE); for (Int32 i = 0; i < FILE_SIZE / 4; i++) { buffer.PutInt32(i); } buffer.Flip(); String path = Path.GetTempFileName(); Byte[] data = new Byte[buffer.Remaining]; buffer.Get(data, 0, data.Length); File.WriteAllBytes(path, data); return(new FileInfo(path)); }
public void Encode(IoSession session, byte[] message, IProtocolEncoderOutput output) { try { var data = (byte[])message; IoBuffer buf = IoBuffer.Allocate(data.Length); buf.AutoExpand = true; // Enable auto-expand for easier encoding buf.Put(data); buf.Flip(); output.Write(buf); } catch (System.Exception ex) { _logger.Error(System.String.Format("Exception in {0} {1}", LST.GetCurrentMethod(), ex.Message)); } }
private void EncodeVoltronStylePackets(IoSession session, IProtocolEncoderOutput output, AriesPacketType ariesType, ushort packetType, IoBufferSerializable message) { var payload = IoBuffer.Allocate(512); payload.Order = ByteOrder.BigEndian; payload.AutoExpand = true; message.Serialize(payload, Context); payload.Flip(); int payloadSize = payload.Remaining; IoBuffer headers = IoBuffer.Allocate(18); headers.Order = ByteOrder.LittleEndian; /** * Aries header * uint32 type * uint32 timestamp * uint32 payloadSize */ uint timestamp = (uint)TimeSpan.FromTicks(DateTime.Now.Ticks - session.CreationTime.Ticks).TotalMilliseconds; headers.PutUInt32(ariesType.GetPacketCode()); headers.PutUInt32(timestamp); headers.PutUInt32((uint)payloadSize + 6); /** * Voltron header * uint16 type * uint32 payloadSize */ headers.Order = ByteOrder.BigEndian; headers.PutUInt16(packetType); headers.PutUInt32((uint)payloadSize + 6); if (payloadSize > 0) { headers.AutoExpand = true; headers.Put(payload); } headers.Flip(); output.Write(headers); //output.Flush(); }
public void Encode(IoSession session, object message, IProtocolEncoderOutput output) { WampCommandBase cmd = (WampCommandBase)message; string json = cmd.toCommandJson(); byte[] jsonByteArray = System.Text.Encoding.UTF8.GetBytes(json); int len = jsonByteArray.Length + 4; if (len > 1000000) { throw new ArgumentException("{msg:'data size > 1m', dataSize:" + len + "}"); } IoBuffer buffer = IoBuffer.Allocate(len); buffer.AutoExpand = true; buffer.PutInt32(len); buffer.Put(jsonByteArray); buffer.Flip(); output.Write(buffer); }
private void ReceiveCallback(IAsyncResult ar) { System.Net.Sockets.Socket socket = (System.Net.Sockets.Socket)ar.AsyncState; Int32 read = 0; try { EndPoint remoteEP = Socket.RemoteEndPoint; read = socket.EndReceiveFrom(ar, ref remoteEP); } catch (ObjectDisposedException) { // do nothing return; } catch (Exception ex) { EndReceive(ex); return; } if (read > 0) { if (ReuseBuffer) { EndReceive(IoBuffer.Wrap(_readBuffer, 0, read)); } else { IoBuffer buf = IoBuffer.Allocate(read); buf.Put(_readBuffer, 0, read); buf.Flip(); EndReceive(buf); } return; } // closed Processor.Remove(this); }
private void EncodeAries(IoSession session, object message, IProtocolEncoderOutput output) { IAriesPacket ariesPacket = (IAriesPacket)message; AriesPacketType ariesPacketType = ariesPacket.GetPacketType(); var payload = IoBuffer.Allocate(128); payload.Order = ByteOrder.LittleEndian; payload.AutoExpand = true; ariesPacket.Serialize(payload, Context); payload.Flip(); int payloadSize = payload.Remaining; IoBuffer headers = IoBuffer.Allocate(12); headers.Order = ByteOrder.LittleEndian; /** * Aries header * uint32 type * uint32 timestamp * uint32 payloadSize */ uint timestamp = (uint)TimeSpan.FromTicks(DateTime.Now.Ticks - session.CreationTime.Ticks).TotalMilliseconds; headers.PutUInt32(ariesPacketType.GetPacketCode()); headers.PutUInt32(timestamp); headers.PutUInt32((uint)payloadSize); if (payloadSize > 0) { headers.AutoExpand = true; headers.Put(payload); } headers.Flip(); output.Write(headers); //output.Flush(); }