/// <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); }
/// <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); }
/// <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)); } }
public void TestUnbindDisconnectsClients() { Bind(true); IoConnector connector = NewConnector(); IoSession[] sessions = new IoSession[5]; for (int i = 0; i < sessions.Length; i++) { IConnectFuture future = connector.Connect(CreateEndPoint(port)); future.Await(); sessions[i] = future.Session; Assert.IsTrue(sessions[i].Connected); Assert.IsTrue(sessions[i].Write(IoBuffer.Allocate(1)).Await().Written); } // Wait for the server side sessions to be created. Thread.Sleep(500); ICollection <IoSession> managedSessions = acceptor.ManagedSessions.Values; Assert.AreEqual(5, managedSessions.Count); acceptor.Unbind(); // Wait for the client side sessions to close. Thread.Sleep(500); //Assert.AreEqual(0, managedSessions.Count); foreach (IoSession element in managedSessions) { Assert.IsFalse(element.Connected); } }
public static IoBuffer SerializableToIoBuffer(object obj, ISerializationContext context) { if (obj is IoBuffer) { var ioBuffer = (IoBuffer)obj; return(ioBuffer); } else if (obj is byte[]) { var byteArray = (byte[])obj; return(IoBuffer.Wrap(byteArray)); } else if (obj is IoBufferSerializable) { var ioBuffer = IoBuffer.Allocate(0); ioBuffer.AutoExpand = true; ioBuffer.Order = ByteOrder.BigEndian; var serializable = (IoBufferSerializable)obj; serializable.Serialize(ioBuffer, context); ioBuffer.Flip(); return(ioBuffer); } throw new Exception("Unknown serializable type: " + obj); }
/// <summary> /// </summary> public IoSessionStream() { _syncRoot = new Byte[0]; _buf = IoBuffer.Allocate(16); _buf.AutoExpand = true; _buf.Limit = 0; }
public IoSessionStream(SslHandler sslHandler) { _sslHandler = sslHandler; _buf = IoBuffer.Allocate(16); _buf.AutoExpand = true; _buf.Limit = 0; }
/// <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); }
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 Encode(IoSession session, object message, IProtocolEncoderOutput output) { if (message is object[]) { foreach (var m in (object[])message) { Encode(session, m, output); } } else if (message is VMNetMessage) { var nmsg = (VMNetMessage)message; var payload = IoBuffer.Allocate(128); payload.Order = ByteOrder.LittleEndian; payload.AutoExpand = true; payload.PutInt32(0); //packet type payload.PutInt32(nmsg.Data.Length + 1); payload.Put((byte)nmsg.Type); foreach (var b in nmsg.Data) { payload.Put(b); } payload.Flip(); output.Write(payload); } }
private void Write(IoSession session, IoBuffer data) { Lazy <IoBuffer> dest = _buffersMap.GetOrAdd(session, new Lazy <IoBuffer>(() => IoBuffer.Allocate(_bufferSize))); Write(session, data, dest.Value); }
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 static IoBuffer Allocate(int size) { IoBuffer buffer = IoBuffer.Allocate(size); buffer.Order = ByteOrder.BigEndian; return(buffer); }
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 IoBuffer SerializeBuffer(object value, ISerializationContext context, bool clsIdPrefix) { var buffer = IoBuffer.Allocate(256); buffer.AutoExpand = true; buffer.Order = ByteOrder.BigEndian; Serialize(buffer, value, context, clsIdPrefix); buffer.Flip(); return(buffer); }
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); }
private void StoreRemainingInSession(IoBuffer buf, IoSession session) { IoBuffer remainingBuf = IoBuffer.Allocate(buf.Capacity); remainingBuf.AutoExpand = true; remainingBuf.Order = buf.Order; remainingBuf.Put(buf); session.SetAttribute(BUFFER, remainingBuf); }
public void Encode(IoSession session, TMessage message, IProtocolEncoderOutput output) { var buffer = IoBuffer.Allocate(48); buffer.AutoExpand = true; if (DoEncode(buffer, message)) { buffer.Flip(); output.Write(buffer); } }
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); }
/// <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 IDecodingState FinishDecode(IProtocolDecoderOutput output) { IoBuffer readData; if (_buffer == null) { readData = IoBuffer.Allocate(0); } else { readData = _buffer.Flip(); _buffer = null; } return(FinishDecode(readData, output)); }
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); }
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 TestDatagramRecycler() { int port = 1024; ExpiringSessionRecycler recycler = new ExpiringSessionRecycler(1, 1); MockHandler acceptorHandler = new MockHandler(); MockHandler connectorHandler = new MockHandler(); acceptor.Handler = acceptorHandler; acceptor.SessionRecycler = recycler; acceptor.Bind(new IPEndPoint(IPAddress.Loopback, port)); try { connector.Handler = connectorHandler; IConnectFuture future = connector.Connect(new IPEndPoint(IPAddress.Loopback, port)); future.Await(); // Write whatever to trigger the acceptor. future.Session.Write(IoBuffer.Allocate(1)).Await(); // Close the client-side connection. // This doesn't mean that the acceptor-side connection is also closed. // The life cycle of the acceptor-side connection is managed by the recycler. future.Session.Close(true); future.Session.CloseFuture.Await(); Assert.IsTrue(future.Session.CloseFuture.Closed); // Wait until the acceptor-side connection is closed. while (acceptorHandler.session == null) { Thread.Yield(); } acceptorHandler.session.CloseFuture.Await(3000); // Is it closed? Assert.IsTrue(acceptorHandler.session.CloseFuture.Closed); Thread.Sleep(1000); Assert.AreEqual("CROPSECL", connectorHandler.result.ToString()); Assert.AreEqual("CROPRECL", acceptorHandler.result.ToString()); } finally { acceptor.Unbind(); } }
public IDecodingState FinishDecode(IProtocolDecoderOutput output) { IoBuffer product; // When input contained only CR or LF rather than actual data... if (_buffer == null) { product = IoBuffer.Allocate(0); } else { product = _buffer.Flip(); _buffer = null; } return(FinishDecode(product, 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); }