private void CheckMessage(NetOutMessage message) { if (message.Array == null) { throw new Exception("NetOutMessage's array is null. Did you Finish() the message?"); } }
/// <summary> /// Queues a message for send through the connection. /// </summary> /// <param name="message">Message to send.</param> public void Send(NetOutMessage message) { if (disposed) { return; } CheckMessage(message); messageQueue.Enqueue(message.Array); messageSentEvent.Set(); }
private void ReceiverWorker() { MessageType messageType = MessageType.Unknown; int messageLength = -1; int messageHeaderCursor = 0; int messageDataCursor = 0; byte[] messageHeader = new byte[NetOutMessage.HeaderSize]; byte[] messageData = null; bool messageStarted = false; byte[] buffer = new byte[receiverBufferSize]; int bytesRead = -1; int bufferCursor = 0; int amountToCopy = 0; while (bytesRead != 0) { //Reading data from connection with disconnect detector try { bytesRead = connection.Receive(buffer); } catch { Log("Connection lost."); break; } bufferCursor = 0; while (bufferCursor < bytesRead) { if (messageHeaderCursor != NetOutMessage.HeaderSize) { //Getting data for the message header amountToCopy = Math.Min(bytesRead - bufferCursor, NetOutMessage.HeaderSize - messageHeaderCursor); if (amountToCopy > 0) { Buffer.BlockCopy(buffer, bufferCursor, messageHeader, messageHeaderCursor, amountToCopy); messageHeaderCursor += amountToCopy; bufferCursor += amountToCopy; } } //If header is completed continue if (messageHeaderCursor == NetOutMessage.HeaderSize) { //Convert header to info and prepair for message data if (!messageStarted) { NetOutMessage.DecodeHeader(messageHeader, out messageType, out messageLength); messageData = new byte[messageLength]; messageStarted = true; } //Copy data in buffer to messageData amountToCopy = Math.Min(bytesRead - bufferCursor, messageLength - messageDataCursor); if (amountToCopy > 0) { Buffer.BlockCopy(buffer, bufferCursor, messageData, messageDataCursor, amountToCopy); messageDataCursor += amountToCopy; bufferCursor += amountToCopy; } //Finish message and reset if (messageDataCursor == messageLength) { OnRawMessageReceived(new NetInMessage(messageType, messageData)); messageStarted = false; messageHeaderCursor = 0; messageDataCursor = 0; messageData = null; } } } } Dispose(); }
/// <summary> /// Sends a message through the connection as soon as possible. /// Also blocks until the message is sent. /// </summary> /// <param name="message">Message to send.</param> public void SendSynchronously(NetOutMessage message) { CheckMessage(message); SocketSend(message.Array); }