public void Dispose() { if (Buffer != null) { ByteArrayPool.Return(Buffer); } }
// send message (via stream) with the <size,content> message structure protected static bool SendMessage(NetworkStream stream, byte[] content) { // can we still write to this socket (not disconnected?) if (!stream.CanWrite) { Logger.LogWarning("Send: stream not writeable: " + stream); return(false); } // check size if (content.Length > ushort.MaxValue) { Logger.LogError("Send: message too big(" + content.Length + ") max=" + ushort.MaxValue); return(false); } // stream.Write throws exceptions if client sends with high // frequency and the server stops try { // write header+content at once via payload array. writing // header,payload separately would cause 2 TCP packets to be // sent if nagle's algorithm is disabled(2x TCP header overhead) byte[] payload = ByteArrayPool.Take(); // construct header (size) UShortToBytes((ushort)content.Length, payload); Array.Copy(content, 0, payload, 2, content.Length); stream.Write(payload, 0, 2 + content.Length); ByteArrayPool.Return(payload); // flush to make sure it is being sent immediately stream.Flush(); return(true); } catch (Exception exception) { // log as regular message because servers do shut down sometimes Logger.Log("Send: stream.Write exception: " + exception); return(false); } }