Пример #1
0
        /// <summary>
        /// Builds a header for a given transmission buffer, then sends the header and body across the network.
        /// </summary>
        /// <param name="buffer">Pre-encoded message body to transmit.</param>
        /// <exception cref="ArgumentException">When an invalid message is passed or was parsed incorrectly.</exception>
        /// <exception cref="IOException">When an error occurs while accessing or writing to the underlying NetworkStream.</exception>
        private void writeBytesToStream(byte[] buffer)
        {
            if (buffer == null || buffer.Length == 0)
            {
                throw new ArgumentException("Raw TCP message cannot be empty.");
            }

            byte[] header = ApplicationLayer.GenerateMessageHeader(buffer.Length);

            lock (stream)
            {
                try
                {
                    stream.Write(header, 0, header.Length);
                    stream.Write(buffer, 0, buffer.Length);
                }
                catch (ObjectDisposedException e)
                {
                    throw new IOException("The underlying NetworkStream object was unexpectedly closed.", e);
                    // TODO: Attempt to reconnect and try to send again.
                }
                catch (Exception e)
                {
                    throw new IOException("An error occurred while writing to the NetworkStream.", e);
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Reads a byte-stream from the network. Handles header parsing to ensure entire message is received
        /// before returning byte[] array of message body.
        /// </summary>
        /// <returns>Byte[] array representing message body.</returns>
        /// <exception cref="IOException">When an error occurs while reading the header or body of an incoming TCP network message.</exception>
        private MemoryStream readMessageFromStream()
        {
            lock (stream)
            {
                waitForData();

                int msgLength = ApplicationLayer.GetMessageLengthFromHeader(stream);

                byte[] msgBuffer = ApplicationLayer.GetMessageBody(stream, msgLength);

                MemoryStream ms = new MemoryStream(msgBuffer);
                return(ms);
            }
        }