public void WriteRequestAndReadResponse()
        {
            var channel = new TcpChannel(8080);

            ChannelServices.RegisterChannel(channel, false);
            RemotingServices.Marshal(new ServiceClass(), "Remote");

            var uri = "tcp://localhost:8080/Remote";

            using (var client = new TcpClient())
            {
                client.Connect("localhost", 8080);
                using (var stream = client.GetStream())
                {
                    var messageRequest = new MethodCall(new Header[] {
                        new Header(MessageHeader.Uri, uri),
                        new Header(MessageHeader.MethodName, "Do"),
                        new Header(MessageHeader.MethodSignature, new Type[] { typeof(string) }),
                        new Header(MessageHeader.TypeName, typeof(ServiceClass).AssemblyQualifiedName),
                        new Header(MessageHeader.Args, new object[] { "Hi" })
                    });
                    var messageRequestStream = BinaryFormatterHelper.SerializeObject(messageRequest);

                    var handle = new TcpProtocolHandle(stream);

                    //send remoting request
                    handle.WritePreamble();
                    handle.WriteMajorVersion();
                    handle.WriteMinorVersion();
                    handle.WriteOperation(TcpOperations.Request);
                    handle.WriteContentDelimiter(TcpContentDelimiter.ContentLength);
                    handle.WriteContentLength(messageRequestStream.Length);
                    handle.WriteTransportHeaders(new Dictionary <string, object>()
                    {
                        { TcpTransportHeader.RequestUri, uri }
                    });
                    handle.WriteContent(messageRequestStream);

                    //read remoting response
                    Console.WriteLine("Preamble: {0}", handle.ReadPreamble());
                    Console.WriteLine("MajorVersion: {0}", handle.ReadMajorVersion());
                    Console.WriteLine("MinorVersion: {0}", handle.ReadMinorVersion());
                    var op = handle.ReadOperation();
                    Assert.AreEqual(TcpOperations.Reply, op);
                    Console.WriteLine("Operation: {0}", op);
                    Console.WriteLine("ContentDelimiter: {0}", handle.ReadContentDelimiter());
                    Console.WriteLine("ContentLength: {0}", handle.ReadContentLength());
                    handle.ReadTransportHeaders();
                    var messageResponse = BinaryFormatterHelper.DeserializeObject(handle.ReadContent()) as MethodResponse;
                    Assert.IsNotNull(messageResponse);
                    DumpHelper.DumpMessage(messageResponse);
                    if (messageResponse.Exception != null)
                    {
                        throw messageResponse.Exception;
                    }
                    Assert.AreEqual("Hi", messageResponse.ReturnValue);
                }
            }
        }
Esempio n. 2
0
        public void ReadRequestAndWriteResponse()
        {
            IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;
            var         endpoint    = new IPEndPoint(addressList[addressList.Length - 1], 9900);
            var         listener    = new TcpListener(endpoint);

            listener.Start();

            var t = new Thread(new ThreadStart(() =>
            {
                var c      = listener.AcceptTcpClient();
                var handle = new HttpProtocolHandle(c.GetStream());

                //read remoting request
                Trace.WriteLine(handle.ReadFirstLine());
                DumpHelper.DumpDictionary(handle.ReadHeaders());
                var messageRequest = BinaryFormatterHelper.DeserializeObject(handle.ReadContent()) as MethodCall;

                //HACK:SoapFormatter not work well
                //http://labs.developerfusion.co.uk/SourceViewer/browse.aspx?assembly=SSCLI&namespace=System.Runtime.Remoting
                //var f = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
                //f.Context = new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Other);
                //var mc = new MethodCall(this.Parse(headers));
                //var messageRequest = f.Deserialize(new System.IO.MemoryStream(content), new HeaderHandler(mc.HeaderHandler));

                Assert.IsNotNull(messageRequest);
                DumpHelper.DumpMessage(messageRequest);

                //write remoting response
                var responeMessage = new MethodResponse(new Header[] { new Header(MessageHeader.Return, messageRequest.Args[0]) }, messageRequest);
                var responseStream = BinaryFormatterHelper.SerializeObject(responeMessage);
                handle.WriteResponseFirstLine("200", "ok");
                handle.WriteHeaders(new Dictionary <string, object>()
                {
                    { HttpHeader.ContentLength, responseStream.Length }
                });
                handle.WriteContent(responseStream);

                //end httprequest
                c.Close();
            }));

            t.Start();

            //use BinaryFormatter via HTTP
            var channel = new HttpChannel(new Hashtable(), new BinaryClientFormatterSinkProvider(), null);

            ChannelServices.RegisterChannel(channel, false);
            var url     = string.Format("http://{0}/remote.rem", endpoint);
            var service = RemotingServices.Connect(typeof(ServiceClass), url) as ServiceClass;

            Assert.AreEqual("Hi", service.Do("Hi"));

            t.Abort();

            ChannelServices.UnregisterChannel(channel);
        }
        public void ReadRequestAndWriteResponse()
        {
            IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;
            var         endpoint    = new IPEndPoint(addressList[addressList.Length - 1], 9900);
            var         listener    = new TcpListener(endpoint);

            listener.Start();

            var t = new Thread(new ThreadStart(() =>
            {
                var c      = listener.AcceptTcpClient();
                var handle = new TcpProtocolHandle(c.GetStream());

                //read remoting request
                Console.WriteLine("Preamble: {0}", handle.ReadPreamble());
                Console.WriteLine("MajorVersion: {0}", handle.ReadMajorVersion());
                Console.WriteLine("MinorVersion: {0}", handle.ReadMinorVersion());
                var op = handle.ReadOperation();
                Assert.AreEqual(TcpOperations.Request, op);
                Console.WriteLine("Operation: {0}", op);
                Console.WriteLine("ContentDelimiter: {0}", handle.ReadContentDelimiter());
                Console.WriteLine("ContentLength: {0}", handle.ReadContentLength());
                DumpHelper.DumpDictionary(handle.ReadTransportHeaders());
                var messageRequest = BinaryFormatterHelper.DeserializeObject(handle.ReadContent()) as MethodCall;
                Assert.IsNotNull(messageRequest);
                DumpHelper.DumpMessage(messageRequest);

                //write remoting response
                var responeMessage = new MethodResponse(new Header[] { new Header(MessageHeader.Return, messageRequest.Args[0]) }, messageRequest);
                var responseStream = BinaryFormatterHelper.SerializeObject(responeMessage);
                handle.WritePreamble();
                handle.WriteMajorVersion();
                handle.WriteMinorVersion();
                handle.WriteOperation(TcpOperations.Reply);
                handle.WriteContentDelimiter(TcpContentDelimiter.ContentLength);
                handle.WriteContentLength(responseStream.Length);
                handle.WriteTransportHeaders(null);
                handle.WriteContent(responseStream);
            }));

            t.Start();

            var url     = string.Format("tcp://{0}/remote.rem", endpoint);
            var service = RemotingServices.Connect(typeof(ServiceClass), url) as ServiceClass;

            Assert.AreEqual("Hi", service.Do("Hi"));

            t.Abort();
        }
Esempio n. 4
0
        public void WriteRequestAndReadResponse()
        {
            var properties = new Hashtable()
            {
                { "port", 8080 }
            };
            var channel = new HttpChannel(properties, null, new BinaryServerFormatterSinkProvider());

            ChannelServices.RegisterChannel(channel, false);
            RemotingServices.Marshal(new ServiceClass(), "Remote");

            var uri = "http://localhost:8080/Remote";

            var messageRequest = new MethodCall(new Header[] {
                new Header(MessageHeader.Uri, uri),
                new Header(MessageHeader.MethodName, "Do"),
                new Header(MessageHeader.MethodSignature, new Type[] { typeof(string) }),
                new Header(MessageHeader.TypeName, typeof(ServiceClass).AssemblyQualifiedName),
                new Header(MessageHeader.Args, new object[] { "Hi" })
            });
            var messageRequestStream = BinaryFormatterHelper.SerializeObject(messageRequest);

            var wc = new WebClient();
            var messageResponse = BinaryFormatterHelper.DeserializeObject(wc.UploadData(uri, messageRequestStream)) as MethodResponse;

            Assert.IsNotNull(messageResponse);
            DumpHelper.DumpMessage(messageResponse);
            if (messageResponse.Exception != null)
            {
                throw messageResponse.Exception;
            }
            Assert.AreEqual("Hi", messageResponse.ReturnValue);

            //handle.WriteRequestFirstLine("POST", "/Remote");
            //handle.WriteHeaders(new Dictionary<string, object>() { { HttpHeader.ContentLength, messageRequestStream.Length } });
            //HACK:http will send 100 continue after read http header
            //handle.WriteContent(messageRequestStream);

            ChannelServices.UnregisterChannel(channel);
        }
        public void WriteRequestAndReadResponse()
        {
            //var properties = new Hashtable() { { "port", 8080 } };
            //var channel = new TcpChannel(properties, null, new SoapServerFormatterSinkProvider());
            //if using SOAP via TCP, messageRequestStream must be SOAP format
            var channel = new TcpChannel(8080);

            ChannelServices.RegisterChannel(channel, false);

            var    service = new ServiceClass();
            ObjRef obj     = RemotingServices.Marshal(service, "Remote");

            var uri = "tcp://localhost:8080/Remote";

            using (var client = new TcpClient())
            {
                client.Connect("localhost", 8080);
                using (var stream = client.GetStream())
                {
                    var messageRequest = new MethodCall(new Header[] {
                        new Header("__Uri", uri),
                        new Header("__MethodName", "Do"),
                        new Header("__MethodSignature", new Type[] { typeof(string) }),
                        new Header("__TypeName", typeof(ServiceClass).AssemblyQualifiedName),
                        new Header("__Args", new object[] { "Hi" })
                    });
                    var messageRequestStream = BinaryFormatterHelper.SerializeObject(messageRequest);

                    var writer = new ProtocolWriter(stream);
                    writer.WritePreamble();
                    writer.WriteMajorVersion();
                    writer.WriteMinorVersion();
                    writer.WriteOperation(TcpOperations.Request);
                    writer.WriteContentDelimiter(TcpContentDelimiter.ContentLength);
                    writer.WriteContentLength(messageRequestStream.Length);
                    writer.WriteTransportHeaders(uri);
                    writer.WriteBytes(messageRequestStream);


                    var reader = new ProtocolReader(stream);
                    Console.WriteLine("Preamble: {0}", reader.ReadPreamble());
                    Console.WriteLine("MajorVersion: {0}", reader.ReadMajorVersion());
                    Console.WriteLine("MinorVersion: {0}", reader.ReadMinorVersion());
                    var op = reader.ReadOperation();
                    Assert.AreEqual(TcpOperations.Reply, op);
                    Console.WriteLine("Operation: {0}", op);
                    Console.WriteLine("ContentDelimiter: {0}", reader.ReadContentDelimiter());
                    var length = reader.ReadContentLength();
                    Console.WriteLine("ContentLength: {0}", length);
                    reader.ReadTransportHeaders();
                    var messageResponse = BinaryFormatterHelper.DeserializeObject(reader.ReadBytes(length)) as MethodResponse;
                    Assert.IsNotNull(messageResponse);
                    DumpHelper.DumpMessage(messageResponse);
                    if (messageResponse.Exception != null)
                    {
                        throw messageResponse.Exception;
                    }
                    Assert.AreEqual("Hi", messageResponse.ReturnValue);
                }
            }
        }
            void ProcessReceive(SocketAsyncEventArgs e)
            {
                if (e.BytesTransferred > 0)
                {
                    if (e.SocketError == SocketError.Success)
                    {
                        totalBuffer = Combine(totalBuffer, e.Buffer);

                        if (e.AcceptSocket.Available == 0)
                        {
                            //.Net Remoting Protocol Parser
                            #region Read Request
                            Console.WriteLine("==== .Net Remoting Protocol Parser ====");
                            //1. Preamble, will be ".NET"
                            Console.WriteLine("Preamble: {0}", Encoding.ASCII.GetString(new byte[] {
                                totalBuffer[0],
                                totalBuffer[1],
                                totalBuffer[2],
                                totalBuffer[3]
                            }));
                            //2. MajorVersion, will be 1
                            Console.WriteLine("MajorVersion: {0}", totalBuffer[4]);
                            //3. MinorVersion, will be 0
                            Console.WriteLine("MinorVersion: {0}", totalBuffer[5]);
                            //4. Operation, will be 5 (request,onewayrequest...)
                            Console.WriteLine("Operation: {0}", (UInt16)(totalBuffer[6] & 0xFF | totalBuffer[7] << 8));
                            //5. TcpContentDelimiter and ContentLength
                            var header = (UInt16)(totalBuffer[8] & 0xFF | totalBuffer[9] << 8);
                            if (header == 1)
                            {
                                Console.WriteLine("Chunked: {0}", true);
                            }
                            else
                            {
                                Console.WriteLine("ContentLength: {0}"
                                                  , (int)((totalBuffer[10] & 0xFF)
                                                          | totalBuffer[11] << 8
                                                          | totalBuffer[12] << 16
                                                          | totalBuffer[13] << 24));
                            }

                            #region 6. ReadHeaders ITransportHeaders
                            Console.WriteLine("---- ITransportHeaders ----");
                            var index      = header == 1 ? 9 : 13;
                            var headerType = ReadUInt16(ref index);
                            while (headerType != TcpHeaders.EndOfHeaders)
                            {
                                if (headerType == TcpHeaders.Custom)
                                {
                                    Console.WriteLine("{0}: {1}", ReadCountedString(ref index), ReadCountedString(ref index));
                                }
                                else if (headerType == TcpHeaders.RequestUri)
                                {
                                    Console.WriteLine("RequestUri-Format: {0}", ReadByte(ref index));
                                    Console.WriteLine("RequestUri: {0}", ReadCountedString(ref index));
                                }
                                else if (headerType == TcpHeaders.StatusCode)
                                {
                                    Console.WriteLine("StatusCode-Format: {0}", ReadByte(ref index));
                                    var code = ReadUInt16(ref index);
                                    Console.WriteLine("StatusCode: {0}", code);
                                    //if (code != 0) error = true;
                                }
                                else if (headerType == TcpHeaders.StatusPhrase)
                                {
                                    Console.WriteLine("StatusPhrase-Format: {0}", ReadByte(ref index));
                                    Console.WriteLine("StatusPhrase: {0}", ReadCountedString(ref index));
                                }
                                else if (headerType == TcpHeaders.ContentType)
                                {
                                    Console.WriteLine("ContentType-Format: {0}", ReadByte(ref index));
                                    Console.WriteLine("ContentType: {0}", ReadCountedString(ref index));
                                }
                                else
                                {
                                    var headerFormat = (byte)ReadByte(ref index);

                                    switch (headerFormat)
                                    {
                                    case TcpHeaderFormat.Void: break;

                                    case TcpHeaderFormat.CountedString: ReadCountedString(ref index); break;

                                    case TcpHeaderFormat.Byte: ReadByte(ref index); break;

                                    case TcpHeaderFormat.UInt16: ReadUInt16(ref index); break;

                                    case TcpHeaderFormat.Int32: ReadInt32(ref index); break;

                                    default:
                                        throw new RemotingException("Remoting_Tcp_UnknownHeaderType");
                                    }
                                }

                                headerType = ReadUInt16(ref index);
                            }
                            #endregion

                            //7. RequestStream/Message
                            var requestStream = new byte[totalBuffer.Length - index - 1];
                            Buffer.BlockCopy(totalBuffer, index + 1, requestStream, 0, totalBuffer.Length - index - 1);
                            //using BinaryFormatterSink default
                            var requestMessage = BinaryFormatterHelper.DeserializeObject(requestStream) as MethodCall;
                            DumpHelper.DumpMessage(requestMessage);
                            #endregion

                            buffers     = new StringBuilder();
                            totalBuffer = new byte[0];

                            #region Write Response

                            //http://labs.developerfusion.co.uk/SourceViewer/browse.aspx?assembly=SSCLI&namespace=System.Runtime.Remoting
                            //else if (name.Equals("__Return"))
                            var responeMessage = new MethodResponse(
                                //just return args[0]
                                new Header[] { new Header("__Return", requestMessage.Args[0]) }
                                , requestMessage);

                            //responeMessage.ReturnValue//can not set
                            var responseStream = BinaryFormatterHelper.SerializeObject(responeMessage);
                            //1.Preamble
                            var preamble = Encoding.ASCII.GetBytes(".NET");
                            foreach (var b in preamble)
                            {
                                WriteByte(b);
                            }
                            //2.MajorVersion
                            WriteByte((byte)1);
                            //3.MinorVersion
                            WriteByte((byte)0);
                            //4.Operation
                            WriteUInt16(TcpOperations.Reply);
                            //5.TcpContentDelimiter and ContentLength
                            WriteUInt16(0);
                            WriteInt32(responseStream.Length);
                            //6.Headers
                            WriteUInt16(TcpHeaders.EndOfHeaders);
                            //7.ResponseStream/Message
                            foreach (var b in responseStream)
                            {
                                WriteByte(b);
                            }
                            #endregion

                            e.SetBuffer(totalBuffer, 0, totalBuffer.Length);
                            if (!e.AcceptSocket.SendAsync(e))
                            {
                                this.ProcessSend(e);
                            }
                        }
                        else if (!e.AcceptSocket.ReceiveAsync(e))
                        {
                            this.ProcessReceive(e);
                        }
                    }
                    else
                    {
                        //this.ProcessError(e);
                    }
                }
                else
                {
                    //this.CloseClientSocket(e);
                }
            }