示例#1
0
        /// <summary>
        /// Writes a message to the underlying stream
        /// </summary>
        /// <param name="message"> The message to write. </param>
        /// <param name="outputStream"> The output stream to write to </param>
        public void WriteMessage(object message, Stream outputStream)
        {
            Type   messageType = message.GetType();
            string typeString  = messageType.AssemblyQualifiedName;

            if (typeString == null)
            {
                throw new ArgumentException(string.Format("Message of type {0} does not have a qualified name", messageType));
            }

            IMessageSerializer serializer = this.factory.CreateSerializer(messageType);

            byte[] messageBytes = serializer.Write(message);
            byte[] typeBytes    = System.Text.Encoding.UTF8.GetBytes(typeString);

            // All bytes should be written in a single go to the underlying transport mechanism.  This is particularly
            // important for named pipes when in message mode as each write is treated as a separate message
            MemoryStream tempBuffer   = new MemoryStream();
            BinaryWriter binaryWriter = new BinaryWriter(tempBuffer);

            binaryWriter.Write(typeBytes.Length);
            binaryWriter.Write(messageBytes.Length);
            binaryWriter.Write(typeBytes);
            binaryWriter.Write(messageBytes);

            byte[] bytes = tempBuffer.ToArray();
            outputStream.Write(bytes, 0, bytes.Length);
        }