using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace pyxis.gemini.Protocol { public class Server { private Request _request; private const int CONNECTION_BUFFER_SIZE = 2048; private byte[] _connection_buffer; private int _connection_buffer_length; public delegate void RequestEventDelegate(Server sender, Request request); public event RequestEventDelegate OnRequest; public Server() { this._connection_buffer = new byte[CONNECTION_BUFFER_SIZE]; this._connection_buffer_length = 0; } public void Receive(byte[] data, int length) { // Copy read bytes into connection buffer for (int i = 0; i < length; i++) { if (i >= CONNECTION_BUFFER_SIZE) { throw new System.Exception("Connection buffer overflow"); } this._connection_buffer[i + this._connection_buffer_length] = data[i]; } this._connection_buffer_length += length; Request r; int consumed = Request.Parse(this._connection_buffer, this._connection_buffer_length, out r); if (consumed == 0) { if (length == 0) { throw new System.Exception("Stream closed without receiving request"); } else { return; } } if (consumed != this._connection_buffer_length) { throw new Exception.ProtocolViolationException("Received trailing bytes after request"); } if (this.OnRequest != null) { this.OnRequest(this, r); } } } }