示例#1
0
        /// <summary>Write a message to a stream</summary>
        private static void MessageToStream(CacheMessage m, Stream s)
        {
            BinaryWriter w = new BinaryWriter(s);

            w.Write(m.MessageType);
            w.Write(IPAddress.HostToNetworkOrder(m.MessageLength));
            if (m.MessageLength > 0)
            {
                w.Write(m.Data);
            }
            w.Flush();
        }
示例#2
0
        /// <summary>Read a message from a stream</summary>
        private static CacheMessage MessageFromStream(Stream s)
        {
            BinaryReader r            = new BinaryReader(s);
            byte         responseType = r.ReadByte();

            int responseLength = IPAddress.NetworkToHostOrder(r.ReadInt32());

            byte[] responseData = r.ReadBytes(responseLength);

            CacheMessage m = new CacheMessage();

            m.MessageType = responseType;
            m.Data        = responseData;

            return(m);
        }
示例#3
0
        /// <summary>
        /// Clients call this method to send a message to a listener.
        /// </summary>
        /// <remarks>Shouldn't be used by the listener since it's not async.</remarks>
        /// <param name="request"></param>
        /// <param name="serverAddress"></param>
        /// <returns></returns>
        public static CacheMessage SendRequest(CacheMessage request, IPEndPoint serverAddress)
        {
            if (request.MessageLength > (1024 * 1024))
            {
                throw new Exception("Message exceeds max data length");
            }

            using (TcpClient client = new TcpClient())
            {
                client.Connect(serverAddress);

                using (NetworkStream stream = client.GetStream())
                {
                    MessageToStream(request, stream);
                    return(MessageFromStream(stream));
                }
            }
        }