Example #1
0
        private IInputChannel RetrieveAsyncChannel(Uri queue, TimeSpan timeout, out IChannelListener parentListener)
        {
            IChannelListener <IInputChannel> listener =
                Util.GetBinding().BuildChannelListener <IInputChannel>(queue, new BindingParameterCollection());

            listener.Open();
            IInputChannel inputChannel;

            try
            {
                IAsyncResult acceptResult = listener.BeginAcceptChannel(timeout, null, null);
                Thread.Sleep(TimeSpan.FromMilliseconds(300.0)); // Dummy work
                inputChannel = listener.EndAcceptChannel(acceptResult);
            }
            catch (TimeoutException)
            {
                listener.Close();
                throw;
            }
            finally
            {
                parentListener = listener;
            }
            return(inputChannel);
        }
        public static void Snippet1()
        {
            // <Snippet1>
            CustomBinding binding = new CustomBinding();

            binding.Elements.Add(new HttpTransportBindingElement());
            BindingParameterCollection       paramCollection = new BindingParameterCollection();
            IChannelListener <IReplyChannel> listener        = binding.BuildChannelListener <IReplyChannel>
                                                                   (new Uri("http://localhost:8000/ChannelApp"), paramCollection);

            listener.Open();
            IReplyChannel channel = listener.AcceptChannel();

            Console.WriteLine("Listening for messages");
            channel.Open();
            RequestContext request = channel.ReceiveRequest();
            Message        msg     = request.RequestMessage;

            Console.WriteLine("Message Received");
            Console.WriteLine("Message Action: {0}", msg.Headers.Action);

            if (msg.Headers.Action == "hello")
            {
                Message reply = Message.CreateMessage(MessageVersion.Default, "wcf");
                request.Reply(reply);
            }

            msg.Close();
            channel.Close();
            listener.Close();
            // </Snippet1>
        }
Example #3
0
        private TObjectType ReceiveMessage <TObjectType>()
        {
            Uri endpoint = new Uri("amqp:message_queue");
            IChannelListener <IInputChannel> listener = Util.GetBinding().BuildChannelListener <IInputChannel>(endpoint, new BindingParameterCollection());

            listener.Open();
            IInputChannel service = listener.AcceptChannel(TimeSpan.FromSeconds(10));

            service.Open();
            Message receivedMessage = service.Receive(TimeSpan.FromSeconds(10));

            Assert.NotNull(receivedMessage, "Message was not received");
            try
            {
                TObjectType receivedObject = receivedMessage.GetBody <TObjectType>();
                return(receivedObject);
            }
            catch (SerializationException)
            {
                Assert.Fail("Deserialized object not of correct type");
            }
            finally
            {
                receivedMessage.Close();
                service.Close();
                listener.Close();
            }

            return(default(TObjectType));
        }
Example #4
0
        public void ServiceRecipientHasNoKeys()
        {
            AsymmetricSecurityBindingElement sbe =
                new AsymmetricSecurityBindingElement();

            sbe.InitiatorTokenParameters =
                new X509SecurityTokenParameters();
            sbe.RecipientTokenParameters =
                new UserNameSecurityTokenParameters();
            //sbe.SetKeyDerivation (false);
            //sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
            CustomBinding binding = new CustomBinding(sbe,
                                                      new HttpTransportBindingElement());
            IChannelListener <IReplyChannel> l =
                binding.BuildChannelListener <IReplyChannel> (new Uri("http://localhost:37564"), new BindingParameterCollection());

            try {
                l.Open();
            } finally {
                if (l.State == CommunicationState.Opened)
                {
                    l.Close();
                }
            }
        }
Example #5
0
        private void ReceiveTryMessages(TimeSpan channelAcceptTimeout, TimeSpan messageReceiveTimeout)
        {
            IChannelListener <IInputChannel> listener = Util.GetBinding().BuildChannelListener <IInputChannel>(this.endpoint, new BindingParameterCollection());

            listener.Open();
            IInputChannel inputChannel  = listener.AcceptChannel(channelAcceptTimeout);
            IAsyncResult  channelResult = inputChannel.BeginOpen(channelAcceptTimeout, null, null);

            Thread.Sleep(TimeSpan.FromMilliseconds(50.0));
            inputChannel.EndOpen(channelResult);

            IAsyncResult[] resultArray = new IAsyncResult[MessageCount];

            for (int i = 0; i < MessageCount; i++)
            {
                resultArray[i] = inputChannel.BeginTryReceive(messageReceiveTimeout, null, null);
            }

            for (int j = 0; j < MessageCount; j++)
            {
                Message tempMessage;
                Assert.True(inputChannel.EndTryReceive(resultArray[j], out tempMessage), "Did not successfully receive message #{0}", j);
            }

            inputChannel.Close();
            listener.Close();
        }
        public void CheckDuplicateAuthenticatorTypesService()
        {
            SymmetricSecurityBindingElement be =
                new SymmetricSecurityBindingElement();

            be.ProtectionTokenParameters =
                new X509SecurityTokenParameters();
            be.EndpointSupportingTokenParameters.Endorsing.Add(
                new X509SecurityTokenParameters());
            // This causes multiple supporting token authenticator
            // of the same type.
            be.OptionalEndpointSupportingTokenParameters.Endorsing.Add(
                new X509SecurityTokenParameters());
            Binding            b    = new CustomBinding(be, new HttpTransportBindingElement());
            ServiceCredentials cred = new ServiceCredentials();

            cred.ServiceCertificate.Certificate =
                new X509Certificate2(TestResourceHelper.GetFullPathOfResource("Test/Resources/test.pfx"), "mono");
            IChannelListener <IReplyChannel> ch = b.BuildChannelListener <IReplyChannel> (new Uri("http://localhost:" + NetworkHelpers.FindFreePort()), cred);

            try {
                ch.Open();
            } finally {
                if (ch.State == CommunicationState.Closed)
                {
                    ch.Close();
                }
            }
        }
Example #7
0
 static void Main(string[] args)
 {
     try
     {
         //建立和发送端相同的通道栈
         BindingElement[] bindingElements = new BindingElement[3];
         bindingElements[0] = new TextMessageEncodingBindingElement();//文本编码
         //oneWayBindingElement() 传输通道支持数据报模式
         bindingElements[1] = new OneWayBindingElement();
         bindingElements[2] = new NamedPipeTransportBindingElement();//命名管道
         CustomBinding binding = new CustomBinding(bindingElements);
         //建立ChannelListner倾听者,接收数据
         IChannelListener <IInputChannel> listener = binding.BuildChannelListener <IInputChannel>(new Uri("net.pipe://localhost/InputService"), new BindingParameterCollection());
         listener.Open();//打开ChannelListner
         IInputChannel inputChannel = listener.AcceptChannel();
         //创建IInputChannel
         inputChannel.Open();                      //打开IInputChannel
         Console.WriteLine("开始接受消息..");
         Message message = inputChannel.Receive(); //接受并打印
         Console.WriteLine($"接收一条消息,action为{message.Headers.Action},Body为{message.GetBody<string>()}");
         message.Close();                          //关闭消息
         inputChannel.Close();                     //关闭通道
         listener.Close();                         //关闭监听器
         Console.Read();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
     finally
     {
         Console.Read();
     }
 }
Example #8
0
        void RunTest()
        {
            listener.Open();
            Thread thread = new Thread(ServerThread);

            thread.Start(this);

            CustomBinding binding = new CustomBinding(new WseTcpTransportBindingElement());
            IChannelFactory <IDuplexSessionChannel> channelFactory = binding.BuildChannelFactory <IDuplexSessionChannel>();

            channelFactory.Open();
            IDuplexSessionChannel channel = channelFactory.CreateChannel(new EndpointAddress(this.uri));
            Message requestMessage;

            channel.Open();
            requestMessage = Message.CreateMessage(binding.MessageVersion, "http://SayHello", "to you.");
            channel.Send(requestMessage);
            Message hello = channel.Receive();

            using (hello)
            {
                Console.WriteLine(hello.GetBody <string>());
            }
            Console.WriteLine("Press enter.");
            Console.ReadLine();
            requestMessage = Message.CreateMessage(binding.MessageVersion, "http://NotHello", "to me.");
            channel.Send(requestMessage);
            channel.Close();
            thread.Join();

            channelFactory.Close();
            listener.Close();
            Console.WriteLine("Press enter.");
            Console.ReadLine();
        }
Example #9
0
 static void Main(string[] args)
 {
     try
     {
         //建立和发送端相同的通道栈
         BindingElement[] bindingElements = new BindingElement[3];
         bindingElements[0] = new TextMessageEncodingBindingElement();
         bindingElements[1] = new OneWayBindingElement();
         bindingElements[2] = new HttpTransportBindingElement();
         CustomBinding binding = new CustomBinding(bindingElements);
         //建立ChannelListner
         IChannelListener <IInputChannel> listener = binding.BuildChannelListener <IInputChannel>(new Uri("http://localhost/InputService"), new BindingParameterCollection());
         listener.Open();
         //创建IInputChannel
         IInputChannel inputChannel = listener.AcceptChannel();
         inputChannel.Open();
         Console.WriteLine("开始接受消息。。。");
         //接受并打印消息
         Message message = inputChannel.Receive();
         Console.WriteLine("接受到一条消息,action为:{0},body为:{1}", message.Headers.Action, message.GetBody <String>());
         message.Close();
         inputChannel.Close();
         listener.Close();
         Console.Read();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
     finally
     {
         Console.Read();
     }
 }
Example #10
0
        public static void Snippet17()
        {
            // <Snippet17>
            CustomBinding binding = new CustomBinding();
            HttpTransportBindingElement element    = new HttpTransportBindingElement();
            BindingParameterCollection  parameters = new BindingParameterCollection();
            Uri            baseAddress             = new Uri("http://localhost:8000/ChannelApp");
            String         relAddress = "http://localhost:8000/ChannelApp/service";
            BindingContext context    = new BindingContext(binding, parameters, baseAddress, relAddress, ListenUriMode.Explicit);

            IChannelListener <IReplyChannel> listener = element.BuildChannelListener <IReplyChannel>(context);

            listener.Open();
            IReplyChannel channel = listener.AcceptChannel();

            channel.Open();
            RequestContext request = channel.ReceiveRequest();
            Message        msg     = request.RequestMessage;

            Console.WriteLine("Message Received");
            Console.WriteLine("Message Action: {0}", msg.Headers.Action);

            if (msg.Headers.Action == "hello")
            {
                Message reply = Message.CreateMessage(MessageVersion.Default, "wcf");
                request.Reply(reply);
            }

            msg.Close();
            channel.Close();
            listener.Close();
            // </Snippet17>
        }
Example #11
0
        private static void ReceiveMessages()
        {
            // Read messages from queue until queue is empty
            Console.WriteLine("Reading messages from queue {0}...", SampleManager.SessionlessQueueName);
            Console.WriteLine("Receiver Type: Receive and Delete");

            // Create channel listener and channel using NetMessagingBinding
            NetMessagingBinding             messagingBinding = new NetMessagingBinding("messagingBinding");
            EndpointAddress                 address          = SampleManager.GetEndpointAddress(SampleManager.SessionlessQueueName, serviceBusNamespace);
            TransportClientEndpointBehavior securityBehavior = new TransportClientEndpointBehavior();

            securityBehavior.TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(serviceBusKeyName, serviceBusKey);

            IChannelListener <IInputChannel> inputChannelListener = null;
            IInputChannel inputChannel = null;

            try
            {
                inputChannelListener = messagingBinding.BuildChannelListener <IInputChannel>(address.Uri, securityBehavior);
                inputChannelListener.Open();
                inputChannel = inputChannelListener.AcceptChannel();
                inputChannel.Open();

                while (true)
                {
                    try
                    {
                        // Receive message from queue. If no more messages available, the operation throws a TimeoutException.
                        Message receivedMessage = inputChannel.Receive(receiveMessageTimeout);
                        SampleManager.OutputMessageInfo("Receive", receivedMessage);

                        // Since the message body contains a serialized string one can access it like this:
                        //string soapBody = receivedMessage.GetBody<string>();
                    }
                    catch (TimeoutException)
                    {
                        break;
                    }
                }

                // Close
                inputChannel.Close();
                inputChannelListener.Close();
            }
            catch (Exception)
            {
                if (inputChannel != null)
                {
                    inputChannel.Abort();
                }
                if (inputChannelListener != null)
                {
                    inputChannelListener.Abort();
                }
                throw;
            }
        }
Example #12
0
        public void Stop()
        {
            if (listener == null)
            {
                throw new InvalidOperationException(ExceptionMessageListenerHasNotBeenStarted);
            }

            listener.Close();
            listener = null;
        }
Example #13
0
        static void RunService()
        {
            //Step1: Create a custom binding with just TCP.
            BindingElement[] bindingElements = new BindingElement[2];
            bindingElements[0] = new TextMessageEncodingBindingElement();
            bindingElements[1] = new HttpTransportBindingElement();

            CustomBinding binding = new CustomBinding(bindingElements);


            //Step2: Use the binding to build the channel listener.
            IChannelListener <IReplyChannel> listener =
                binding.BuildChannelListener <IReplyChannel>(
                    new Uri("http://localhost:8080/channelapp"),
                    new BindingParameterCollection());

            //Step3: Listening for messages.
            listener.Open();
            Console.WriteLine(
                "Listening for incoming channel connections");
            //Wait for and accept incoming connections.
            IReplyChannel channel = listener.AcceptChannel();

            Console.WriteLine("Channel accepted. Listening for messages");
            //Open the accepted channel.
            channel.Open();
            //Wait for and receive a message from the channel.
            RequestContext request = channel.ReceiveRequest();
            //Step4: Reading the request message.
            Message message = request.RequestMessage;

            Console.WriteLine("Message received");
            Console.WriteLine("Message action: {0}",
                              message.Headers.Action);
            string data = message.GetBody <string>();

            Console.WriteLine("Message content: {0}", data);
            //Send a reply.
            Message replymessage = Message.CreateMessage(
                binding.MessageVersion,
                "http://contoso.com/someotheraction",
                data);

            request.Reply(replymessage);
            //Step5: Closing objects.
            //Do not forget to close the message.
            message.Close();
            //Do not forget to close RequestContext.
            request.Close();
            //Do not forget to close channels.
            channel.Close();
            //Do not forget to close listeners.
            listener.Close();
        }
Example #14
0
        static void Main(string[] args)
        {
            try
            {
                //建立和发送端相同的通道栈
                BindingElement[] bindingElements = new BindingElement[2];
                bindingElements[0] = new TextMessageEncodingBindingElement();
                bindingElements[1] = new HttpTransportBindingElement();
                CustomBinding binding = new CustomBinding(bindingElements);

                //建立ChannelListener
                IChannelListener <IReplyChannel> listener = binding.BuildChannelListener <IReplyChannel>(
                    new Uri("http://localhost:9090/RequestReplyService"),
                    new BindingParameterCollection());
                listener.Open();       //打开监听

                //创建IReplyChannel
                IReplyChannel replyChannel = listener.AcceptChannel();
                replyChannel.Open();   //打开通道

                Console.WriteLine("开始接收消息");

                //接收并打印消息
                RequestContext requestContext = replyChannel.ReceiveRequest();     //会堵塞在这里

                Console.WriteLine("接收到一条消息, action为{0}, body为{1}",
                                  requestContext.RequestMessage.Headers.Action,
                                  requestContext.RequestMessage.GetBody <string>());

                //创建返回消息
                Message response = Message.CreateMessage(binding.MessageVersion, "response", "response body");

                //发送返回消息
                requestContext.Reply(response);

                requestContext.Close();
                replyChannel.Close();
                listener.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
        }
Example #15
0
        void AcceptCallback(object state)
        {
            IChannelListener <IReplyChannel> listener = (IChannelListener <IReplyChannel>)state;

            this.acceptedChannel = listener.AcceptChannel(TimeSpan.MaxValue);
            if (this.acceptedChannel != null)
            {
                this.acceptedChannel.Open();
                ReceiveRequest(this.acceptedChannel);
            }
            else
            {
                listener.Close();
            }
        }
Example #16
0
        private void BasicChannelTestB(bool customBinding)
        {
            IChannelListener <IReplyChannel> listener = null;
            IReplyChannel    channel = null;
            ManualResetEvent done    = new ManualResetEvent(false);
            Thread           t       = null;

            try
            {
                channel = this.OpenChannel(customBinding, out listener);
                Assert.IsNotNull(channel);
                Assert.IsNotNull(listener);

                t = new Thread(BasicChannelTests.SubmitRequests);
                t.Start(done);

                for (var cnt = 0; cnt < TestServiceCommon.Iterations; cnt++)
                {
                    RequestContext context;
                    if (channel.TryReceiveRequest(TestServiceCommon.DefaultHostTimeout, out context))
                    {
                        this.SendResponse(context);
                    }
                    else
                    {
                        Assert.Fail("TryReceiveRequest failed.");
                    }
                }

                channel.Close(TestServiceCommon.DefaultHostTimeout);
                listener.Close(TestServiceCommon.DefaultHostTimeout);
            }
            catch (Exception e)
            {
                channel.Abort();
                listener.Abort();
                Assert.Fail("Unexpected exception: " + e);
            }
            finally
            {
                if (t != null && !done.WaitOne(TestServiceCommon.DefaultHostTimeout))
                {
                    t.Abort();
                }

                done.Dispose();
            }
        }
Example #17
0
        private void ReceiveMessage <TObjectType>(TObjectType objectToMatch, AmqpProperties expectedProperties)
        {
            Uri receiveFromUri = new Uri("amqp:message_queue");
            IChannelListener <IInputChannel> listener = Util.GetBinding().BuildChannelListener <IInputChannel>(receiveFromUri, new BindingParameterCollection());

            listener.Open();
            IInputChannel service = listener.AcceptChannel(TimeSpan.FromSeconds(10));

            service.Open();
            Message receivedMessage = service.Receive(TimeSpan.FromSeconds(10));

            try
            {
                TObjectType receivedObject = receivedMessage.GetBody <TObjectType>();
                Assert.True(receivedObject.Equals(objectToMatch), "Original and deserialized objects do not match");

                AmqpProperties receivedProperties = (AmqpProperties)receivedMessage.Properties["AmqpProperties"];
                PropertyInfo[] propInfo           = typeof(AmqpProperties).GetProperties();

                for (int i = 0; i < propInfo.Length; i++)
                {
                    string propertyName = propInfo[i].Name;
                    if (propertyName.Equals("RoutingKey", StringComparison.InvariantCultureIgnoreCase))
                    {
                        Assert.AreEqual(RoutingKey, Convert.ToString(propInfo[i].GetValue(receivedProperties, null)));
                    }
                    else
                    {
                        Assert.AreEqual(Convert.ToString(propInfo[i].GetValue(expectedProperties, null)), Convert.ToString(propInfo[i].GetValue(receivedProperties, null)));
                    }
                }
            }
            catch (NullReferenceException)
            {
                Assert.Fail("Message not received");
            }
            catch (SerializationException)
            {
                Assert.Fail("Deserialized object not of correct type");
            }
            finally
            {
                receivedMessage.Close();
                service.Close();
                listener.Close();
            }
        }
Example #18
0
        public static void Main()
        {
            CustomBinding binding = new CustomBinding();

            binding.Elements.Add(new TextMessageEncodingBindingElement());
            binding.Elements.Add(new TcpTransportBindingElement());

            BindingParameterCollection bpcol =
                new BindingParameterCollection();

//			using (IChannelListener<IDuplexSessionChannel> listener =
//				binding.BuildChannelListener<IDuplexSessionChannel> (
//					new Uri ("net.tcp://localhost/Server"), bpcol))
//			{
            IChannelListener <IDuplexSessionChannel> listener =
                binding.BuildChannelListener <IDuplexSessionChannel> (
                    new Uri("net.tcp://localhost/"), bpcol);

            listener.Open();

            IDuplexSessionChannel channel =
                listener.AcceptChannel();

            Console.WriteLine("Listening for messages...");

            channel.Open();

            Message message = channel.Receive();

            Console.WriteLine("Message received.");
            Console.WriteLine("Message action: {0}",
                              message.Headers.Action);
            Console.WriteLine("Message content: {0}",
                              message.GetBody <string> ());

            message = Message.CreateMessage(
                //channel.Manager.MessageVersion,
                MessageVersion.Default,
                "Action", "Hello, World, from service side");

            channel.Send(message);

            message.Close();
            channel.Close();
            listener.Close();
//			}
        }
        public void CustomTransportDoesNotRequireMessageEncoding()
        {
            ReplyHandler replier = delegate(Message msg)
            {
                resmsg = msg;
            };

            RequestReceiver receiver = delegate()
            {
                return(reqmsg);
            };

            RequestSender sender = delegate(Message msg)
            {
                reqmsg = msg;

                CustomBinding br = new CustomBinding(
                    new HandlerTransportBindingElement(replier, receiver));
                IChannelListener <IReplyChannel> l =
                    br.BuildChannelListener <IReplyChannel> (
                        new BindingParameterCollection());
                l.Open();
                IReplyChannel rch = l.AcceptChannel();
                rch.Open();
                Message res = Message.CreateMessage(MessageVersion.Default, "urn:succeeded");
                rch.ReceiveRequest().Reply(res);
                rch.Close();
                l.Close();

                return(resmsg);
            };

            CustomBinding bs = new CustomBinding(
                new HandlerTransportBindingElement(sender));

            IChannelFactory <IRequestChannel> f =
                bs.BuildChannelFactory <IRequestChannel> (
                    new BindingParameterCollection());

            f.Open();
            IRequestChannel ch = f.CreateChannel(new EndpointAddress("urn:dummy"));

            ch.Open();
            Message result = ch.Request(Message.CreateMessage(MessageVersion.Default, "urn:request"));
        }
Example #20
0
        public override void Run(string listenUri)
        {
            IChannelListener <IInputChannel> listener = this.Binding.BuildChannelListener <IInputChannel>(new Uri(listenUri));

            listener.Open();

            if (this.Parameters.WaitForChannel)
            {
                this.WaitForChannel(listener, this.Parameters.AsyncWaitForChannel, this.Parameters.WaitForChannelTimeout);
            }

            this.AcceptChannelAndReceive(listener);

            if (listener.State != CommunicationState.Closed)
            {
                listener.Close();
            }
        }
Example #21
0
        private IInputChannel CreateInputChannel(BufferManager bufferManager, string queueName)
        {
            Uri listenUriBaseAddress = new Uri(string.Format("amqp://{0}:{1}/{2}", _host, _port, queueName));

            object[] parameters = CreateParameters(bufferManager);

            IChannelListener <IInputChannel> listener = _binding.BuildChannelListener <IInputChannel>(listenUriBaseAddress, parameters);

            listener.Open();

            try
            {
                return(listener.AcceptChannel());
            }
            finally
            {
                listener.Close();
            }
        }
Example #22
0
        public IDuplexChannel CreateChannel(EndpointAddress remoteAddress, Uri via, EndpointAddress localAddress, MessageFilter filter, int priority, bool usesUniqueHeader)
        {
            ChannelDemuxerFilter             demuxFilter        = new ChannelDemuxerFilter(new AndMessageFilter(new EndpointAddressMessageFilter(localAddress, true), filter), priority);
            IDuplexChannel                   newChannel         = null;
            IOutputChannel                   innerOutputChannel = null;
            IChannelListener <IInputChannel> innerInputListener = null;
            IInputChannel innerInputChannel = null;

            try
            {
                innerOutputChannel = this.innerChannelFactory.CreateChannel(remoteAddress, via);
                innerInputListener = this.channelDemuxer.BuildChannelListener <IInputChannel>(demuxFilter);
                innerInputListener.Open();
                innerInputChannel = innerInputListener.AcceptChannel();
                newChannel        = new ClientCompositeDuplexChannel(this, innerInputChannel, innerInputListener, localAddress, innerOutputChannel, usesUniqueHeader);
            }
            finally
            {
                if (newChannel == null) // need to cleanup
                {
                    if (innerOutputChannel != null)
                    {
                        innerOutputChannel.Close();
                    }

                    if (innerInputListener != null)
                    {
                        innerInputListener.Close();
                    }

                    if (innerInputChannel != null)
                    {
                        innerInputChannel.Close();
                    }
                }
            }

            return(newChannel);
        }
Example #23
0
 static void Main(string[] args)
 {
     try
     {
         //使用说明先启动input,然后在启动启动output。
         //记得使用管理员启动VS,我在程序清单中添加了管理员权限。
         //建立和发送端相同的通道栈
         BindingElement[] bindingElements = new BindingElement[2];
         bindingElements[0] = new TextMessageEncodingBindingElement(); //文本编码
         bindingElements[1] = new HttpTransportBindingElement();       //HTTP传输
         CustomBinding binding = new CustomBinding(bindingElements);
         //建立ChannelListner
         IChannelListener <IReplyChannel> listener = binding.BuildChannelListener <IReplyChannel>(new Uri("http://localhost:9090/RequestReplyService"), new BindingParameterCollection());
         listener.Open();//打开监听
         //创建IRepllyChannel
         IReplyChannel replyChannel = listener.AcceptChannel();
         replyChannel.Open();//打开通道
         Console.WriteLine("开始接受消息..");
         //接收打印
         RequestContext requestContext = replyChannel.ReceiveRequest();
         Console.WriteLine($"接收到一条消息,action为:{requestContext.RequestMessage.Headers.Action},body为{requestContext.RequestMessage.GetBody<string>()}");
         //创建返回消息
         Message response = Message.CreateMessage(binding.MessageVersion, "response", "reponse body");
         //发送返回消息
         requestContext.Reply(response);
         //关闭
         requestContext.Close(); //关闭通道
         listener.Close();       //关闭监听
         Console.Read();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
     finally
     {
         Console.Read();
     }
 }
Example #24
0
        internal override IInputChannel OnCreateInputChannel(SubscriberConfigurator configuration)
        {
            Uri listenUriBaseAddress = CreateUri();

            object[] parameters = CreateParameters(configuration.BufferManager);

            IChannelListener <IInputChannel> listener = _binding.BuildChannelListener <IInputChannel>(listenUriBaseAddress, parameters);

            listener.Open();

            IInputChannel channel;

            try
            {
                channel = listener.AcceptChannel();
            }
            finally
            {
                listener.Close();
            }

            return(channel);
        }
Example #25
0
        public static int GetMessageCountFromQueue(string listenUri)
        {
            Message receivedMessage = null;
            int     messageCount    = 0;

            IChannelListener <IInputChannel> listener = Util.GetBinding().BuildChannelListener <IInputChannel>(new Uri(listenUri), new BindingParameterCollection());

            listener.Open();
            IInputChannel proxy = listener.AcceptChannel(TimeSpan.FromSeconds(10));

            proxy.Open();

            while (true)
            {
                try
                {
                    receivedMessage = proxy.Receive(TimeSpan.FromSeconds(3));
                }
                catch (Exception e)
                {
                    if (e.GetType() == typeof(TimeoutException))
                    {
                        break;
                    }
                    else
                    {
                        throw;
                    }
                }

                messageCount++;
            }

            listener.Close();
            return(messageCount);
        }
Example #26
0
        private void AcceptChannelAndReceive(IChannelListener<IInputChannel> listener)
        {
            IInputChannel channel;
            TransactionScope transactionToAbortOnAccept = null;

            if (this.Parameters.AbortTxDatagramAccept)
            {
                transactionToAbortOnAccept = new TransactionScope(TransactionScopeOption.RequiresNew);
            }

            if (this.Parameters.AsyncAccept)
            {
                IAsyncResult result = listener.BeginAcceptChannel(null, null);
                channel = listener.EndAcceptChannel(result);
            }
            else
            {
                channel = listener.AcceptChannel();
            }

            if (this.Parameters.AbortTxDatagramAccept)
            {
                transactionToAbortOnAccept.Dispose();
            }

            channel.Open();
            Message message;

            if (this.Parameters.CloseListenerEarly)
            {
                listener.Close();
            }

            try
            {
                using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    Message firstMessage = channel.Receive(this.Parameters.ReceiveTimeout);

                    lock (this.Results)
                    {
                        this.Results.Add(String.Format("Received message with Action '{0}'", firstMessage.Headers.Action));
                    }

                    ts.Complete();
                }
            }
            catch (TimeoutException)
            {
                lock (this.Results)
                {
                    this.Results.Add("Receive timed out.");
                }

                channel.Abort();
                return;
            }

            AutoResetEvent doneReceiving = new AutoResetEvent(false);
            int threadsCompleted = 0;

            for (int i = 0; i < this.Parameters.NumberOfThreads; ++i)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object unused)
                {
                    do
                    {
                        if (this.Parameters.ReceiverShouldAbort)
                        {
                            this.ReceiveMessage(channel, false);
                            Thread.Sleep(200);
                        }

                        message = this.ReceiveMessage(channel, true);
                    }
                    while (message != null);

                    if (Interlocked.Increment(ref threadsCompleted) == this.Parameters.NumberOfThreads)
                    {
                        doneReceiving.Set();
                    }
                }));
            }

            TimeSpan threadTimeout = TimeSpan.FromMinutes(2.0);
            if (!doneReceiving.WaitOne(threadTimeout, false))
            {
                this.Results.Add(String.Format("Threads did not complete within {0}.", threadTimeout));
            }

            channel.Close();
        }
Example #27
0
 protected override void OnClose(TimeSpan timeout)
 {
     inner.Close(timeout);
 }
 protected override void OnClose(TimeSpan timeout)
 {
     ReleaseTokens();
     inner.Close(timeout);
 }
Example #29
0
 protected override void OnClose(TimeSpan timeout)
 {
     inner_listener.Close(timeout);
     txscope.Complete();
 }
Example #30
0
        static void Main(string[] args)
        {
            // Creating the Channel
            string channelName = "EMailHelloWorld";

            string serverAddress          = "*****@*****.**";
            string serverPWD              = "MyPassword";
            string clientAddress          = "*****@*****.**";
            string exchangeServerLocation = "http://example.com";

            ExchangeWebServiceMailBinding binding =
                new ExchangeWebServiceMailBinding(
                    new Uri(exchangeServerLocation),
                    new System.Net.NetworkCredential(serverAddress,
                                                     serverPWD));
            BindingParameterCollection parameters =
                new BindingParameterCollection();

            IChannelListener <IInputChannel> listener =
                binding.BuildChannelListener <IInputChannel>
                    (MailUriHelper.CreateUri(channelName, ""), parameters);

            listener.Open();

            // Opening the Channel
            IInputChannel inputChannel = listener.AcceptChannel();

            inputChannel.Open(TimeSpan.MaxValue);
            Console.WriteLine("Channel Open");

            // Waiting and receiving the Message
            Message reply = inputChannel.Receive(TimeSpan.MaxValue);

            Console.WriteLine("Message Recieved");
            XmlSerializerWrapper wrapper = new XmlSerializerWrapper(
                typeof(TransmittedObject));
            TransmittedObject to = reply.GetBody <TransmittedObject>(wrapper);

            // Processing the Message
            to.str = to.str + " World";
            to.i   = to.i + 1;

            Console.WriteLine("Response: " + to.str + " " + to.i.ToString());

            // Creating and returning the Message
            Message m = Message.CreateMessage(binding.MessageVersion,
                                              "urn:test", to, wrapper);

            IChannelFactory <IOutputChannel> channelFactory =
                binding.BuildChannelFactory <IOutputChannel>(parameters);

            channelFactory.Open();

            IOutputChannel outChannel = channelFactory.CreateChannel(
                new EndpointAddress(
                    MailUriHelper.CreateUri(channelName, clientAddress)));

            outChannel.Open();

            Console.WriteLine("Out Channel Open");

            // Sending the Message over the OutChannel
            outChannel.Send(m);

            Console.WriteLine("Message Sent");

            // Cleaning up
            outChannel.Close();
            channelFactory.Close();

            listener.Close();
            inputChannel.Close();
            binding.Close();
        }
Example #31
0
        private void AcceptChannelAndReceive(IChannelListener <IInputChannel> listener)
        {
            IInputChannel    channel;
            TransactionScope transactionToAbortOnAccept = null;

            if (this.Parameters.AbortTxDatagramAccept)
            {
                transactionToAbortOnAccept = new TransactionScope(TransactionScopeOption.RequiresNew);
            }

            if (this.Parameters.AsyncAccept)
            {
                IAsyncResult result = listener.BeginAcceptChannel(null, null);
                channel = listener.EndAcceptChannel(result);
            }
            else
            {
                channel = listener.AcceptChannel();
            }

            if (this.Parameters.AbortTxDatagramAccept)
            {
                transactionToAbortOnAccept.Dispose();
            }

            channel.Open();
            Message message;

            if (this.Parameters.CloseListenerEarly)
            {
                listener.Close();
            }

            try
            {
                using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    Message firstMessage = channel.Receive(this.Parameters.ReceiveTimeout);

                    lock (this.Results)
                    {
                        this.Results.Add(String.Format("Received message with Action '{0}'", firstMessage.Headers.Action));
                    }

                    ts.Complete();
                }
            }
            catch (TimeoutException)
            {
                lock (this.Results)
                {
                    this.Results.Add("Receive timed out.");
                }

                channel.Abort();
                return;
            }

            AutoResetEvent doneReceiving    = new AutoResetEvent(false);
            int            threadsCompleted = 0;

            for (int i = 0; i < this.Parameters.NumberOfThreads; ++i)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object unused)
                {
                    do
                    {
                        if (this.Parameters.ReceiverShouldAbort)
                        {
                            this.ReceiveMessage(channel, false);
                            Thread.Sleep(200);
                        }

                        message = this.ReceiveMessage(channel, true);
                    }while (message != null);

                    if (Interlocked.Increment(ref threadsCompleted) == this.Parameters.NumberOfThreads)
                    {
                        doneReceiving.Set();
                    }
                }));
            }

            TimeSpan threadTimeout = TimeSpan.FromMinutes(2.0);

            if (!doneReceiving.WaitOne(threadTimeout, false))
            {
                this.Results.Add(String.Format("Threads did not complete within {0}.", threadTimeout));
            }

            channel.Close();
        }