Пример #1
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));
        }
Пример #2
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();
     }
 }
Пример #3
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();
     }
 }
Пример #4
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;
            }
        }
Пример #5
0
 void worker(TimeSpan timeout, object state)
 {
     try
     {
         IInputChannel inputChannel = ChannelListener.AcceptChannel(timeout);
         Message       message      = inputChannel.Receive();
         Runtime.PublishOneWay(new PublishRequest(typeof(IPassThroughServiceContract), message.Headers.Action, message));
     }
     catch (TimeoutException)
     {
     }
 }
Пример #6
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();
            }
        }
Пример #7
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);
        }
Пример #8
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();
        }
Пример #9
0
        private Message ReceiveMessage(IInputChannel channel, bool commit)
        {
            Message message = null;

            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required))
            {
                bool messageDetected = false;
                if (this.Parameters.AsyncWaitForMessage)
                {
                    IAsyncResult result = channel.BeginWaitForMessage(this.Parameters.WaitForMessageTimeout, null, null);
                    messageDetected = channel.EndWaitForMessage(result);
                }
                else
                {
                    messageDetected = channel.WaitForMessage(this.Parameters.WaitForMessageTimeout);
                }

                if (this.Parameters.WaitForMessage)
                {
                    lock (this.Results)
                    {
                        this.Results.Add(String.Format("WaitForMessage returned {0}", messageDetected));
                    }
                }

                if (messageDetected)
                {
                    if (this.Parameters.AsyncReceive)
                    {
                        if (this.Parameters.TryReceive)
                        {
                            IAsyncResult result = channel.BeginTryReceive(this.Parameters.ReceiveTimeout, null, null);
                            bool ret = channel.EndTryReceive(result, out message);

                            lock (this.Results)
                            {
                                this.Results.Add(String.Format("TryReceive returned {0}", ret));
                            }
                        }
                        else
                        {
                            try
                            {
                                IAsyncResult result = channel.BeginReceive(this.Parameters.ReceiveTimeout, null, null);
                                message = channel.EndReceive(result);
                            }
                            catch (TimeoutException)
                            {
                                message = null;
                            }
                        }
                    }
                    else
                    {
                        if (this.Parameters.TryReceive)
                        {
                            bool ret = channel.TryReceive(this.Parameters.ReceiveTimeout, out message);

                            lock (this.Results)
                            {
                                this.Results.Add(String.Format("TryReceive returned {0}", ret));
                            }
                        }
                        else
                        {
                            try
                            {
                                message = channel.Receive(this.Parameters.ReceiveTimeout);
                            }
                            catch (TimeoutException)
                            {
                                message = null;
                            }
                        }
                    }
                }
                else
                {
                    if (this.Parameters.TryReceive)
                    {
                        bool ret = false;
                        if (this.Parameters.AsyncReceive)
                        {
                            IAsyncResult result = channel.BeginTryReceive(this.Parameters.ReceiveTimeout, null, null);
                            if (this.Parameters.TryReceiveNullIAsyncResult)
                            {
                                try
                                {
                                    channel.EndTryReceive(null, out message);
                                }
                                catch (Exception e)
                                {
                                    lock (this.Results)
                                    {
                                        this.Results.Add(String.Format("TryReceive threw {0}", e.GetType().Name));
                                    }
                                }
                            }

                            ret = channel.EndTryReceive(result, out message);
                        }
                        else
                        {
                            ret = channel.TryReceive(this.Parameters.ReceiveTimeout, out message);
                        }

                        lock (this.Results)
                        {
                            this.Results.Add(String.Format("TryReceive returned {0}", ret));
                            this.Results.Add(String.Format("Message was {0}", (message == null ? "null" : "not null")));
                        }
                    }

                    message = null;
                }

                if (commit && message != null)
                {
                    lock (this.Results)
                    {
                        this.Results.Add(String.Format("Received message with Action '{0}'", message.Headers.Action));
                    }

                    ts.Complete();
                }
                else
                {
                    Transaction.Current.Rollback();
                }
            }

            return message;
        }
Пример #10
0
        public void Run()
        {
            IRawBodyUtility bodyUtil = new RawEncoderUtility();

            IOutputChannel readyQueue = null;
            IOutputChannel doneQueue  = null;
            UInt64         batchSize  = (UInt64)opts.subTxSize;
            bool           txPending  = false;

            byte[] data = null;

            try
            {
                this.subscribeQueue = QueueChannelFactory.CreateReaderChannel(this.queue);
                readyQueue          = QueueChannelFactory.CreateWriterChannel("", this.Fqn("sub_ready"));
                doneQueue           = QueueChannelFactory.CreateWriterChannel("", this.Fqn("sub_done"));

                Message msg = bodyUtil.CreateMessage("ready");
                readyQueue.Send(msg, TimeSpan.MaxValue);
                msg.Close();


                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                Console.WriteLine("receiving {0}", this.msgCount);
                UInt64 expect = 0;

                if (batchSize > 0)
                {
                    Transaction.Current = new CommittableTransaction();
                }

                for (UInt64 i = 0; i < this.msgCount; i++)
                {
                    msg = subscribeQueue.Receive(TimeSpan.MaxValue);

                    data = bodyUtil.GetBytes(msg, data);
                    msg.Close();
                    if (data.Length != this.msgSize)
                    {
                        throw new Exception("subscribe message size mismatch");
                    }

                    UInt64 n = GetSequenceNumber(data);
                    if (n != expect)
                    {
                        throw new Exception(String.Format("message sequence error. expected {0} got {1}", expect, n));
                    }
                    expect = n + 1;

                    if (batchSize > 0)
                    {
                        txPending = true;
                        if (((i + 1) % batchSize) == 0)
                        {
                            ((CommittableTransaction)Transaction.Current).Commit();
                            txPending           = false;
                            Transaction.Current = new CommittableTransaction();
                        }
                    }
                }

                if (txPending)
                {
                    ((CommittableTransaction)Transaction.Current).Commit();
                }

                Transaction.Current = null;

                stopwatch.Stop();

                double mps = (msgCount / stopwatch.Elapsed.TotalSeconds);

                msg = bodyUtil.CreateMessage(String.Format("{0:0.##}", mps));
                doneQueue.Send(msg, TimeSpan.MaxValue);
                msg.Close();

                subscribeQueue.Close();
            }
            finally
            {
                Close((IChannel)doneQueue);
                Close((IChannel)this.subscribeQueue);
                Close(readyQueue);
            }
        }
Пример #11
0
        public void Run()
        {
            IRawBodyUtility bodyUtil = new RawEncoderUtility();

            IInputChannel  startQueue     = null;
            IOutputChannel doneQueue      = null;
            UInt64         batchSize      = (UInt64)opts.pubTxSize;
            bool           txPending      = false;
            AmqpProperties amqpProperties = null;

            if (opts.durable)
            {
                amqpProperties         = new AmqpProperties();
                amqpProperties.Durable = true;
            }

            try
            {
                publishQueue = QueueChannelFactory.CreateWriterChannel(this.destination, this.routingKey);
                doneQueue    = QueueChannelFactory.CreateWriterChannel("", this.Fqn("pub_done"));
                startQueue   = QueueChannelFactory.CreateReaderChannel(this.Fqn("pub_start"));

                // wait for our start signal
                Message msg;
                msg = startQueue.Receive(TimeSpan.MaxValue);
                Expect(bodyUtil.GetText(msg), "start");
                msg.Close();

                Stopwatch     stopwatch    = new Stopwatch();
                AsyncCallback sendCallback = new AsyncCallback(this.AsyncSendCB);

                byte[]       data       = new byte[this.msgSize];
                IAsyncResult sendResult = null;

                Console.WriteLine("sending {0}", this.msgCount);
                stopwatch.Start();

                if (batchSize > 0)
                {
                    Transaction.Current = new CommittableTransaction();
                }

                for (UInt64 i = 0; i < this.msgCount; i++)
                {
                    StampSequenceNo(data, i);
                    msg = bodyUtil.CreateMessage(data);
                    if (amqpProperties != null)
                    {
                        msg.Properties.Add("AmqpProperties", amqpProperties);
                    }

                    sendResult = publishQueue.BeginSend(msg, TimeSpan.MaxValue, sendCallback, msg);

                    if (batchSize > 0)
                    {
                        txPending = true;
                        if (((i + 1) % batchSize) == 0)
                        {
                            ((CommittableTransaction)Transaction.Current).Commit();
                            txPending           = false;
                            Transaction.Current = new CommittableTransaction();
                        }
                    }
                }

                if (txPending)
                {
                    ((CommittableTransaction)Transaction.Current).Commit();
                }

                Transaction.Current = null;

                sendResult.AsyncWaitHandle.WaitOne();
                stopwatch.Stop();

                double mps = (msgCount / stopwatch.Elapsed.TotalSeconds);

                msg = bodyUtil.CreateMessage(String.Format("{0:0.##}", mps));
                doneQueue.Send(msg, TimeSpan.MaxValue);
                msg.Close();
            }
            finally
            {
                Close((IChannel)doneQueue);
                Close((IChannel)publishQueue);
                Close(startQueue);
            }
        }
Пример #12
0
        static void Main(string[] args)
        {
            String broker = "localhost";
            int    port   = 5672;
            String target = "amq.topic";
            String source = "my_topic_node";

            if (args.Length > 0)
            {
                broker = args[0];
            }

            if (args.Length > 1)
            {
                port = int.Parse(args[1]);
            }

            if (args.Length > 2)
            {
                target = args[2];
            }

            if (args.Length > 3)
            {
                source = args[3];
            }

            AmqpBinaryBinding binding = new AmqpBinaryBinding();

            binding.BrokerHost = broker;
            binding.BrokerPort = port;

            IChannelFactory <IInputChannel> receiverFactory = binding.BuildChannelFactory <IInputChannel>();

            receiverFactory.Open();
            IInputChannel receiver = receiverFactory.CreateChannel(new EndpointAddress("amqp:" + source));

            receiver.Open();

            IChannelFactory <IOutputChannel> senderFactory = binding.BuildChannelFactory <IOutputChannel>();

            senderFactory.Open();
            IOutputChannel sender = senderFactory.CreateChannel(new EndpointAddress("amqp:" + target));

            sender.Open();

            sender.Send(Message.CreateMessage(MessageVersion.None, "", new HelloWorldBinaryBodyWriter()));

            Message             message = receiver.Receive();
            XmlDictionaryReader reader  = message.GetReaderAtBodyContents();

            while (!reader.HasValue)
            {
                reader.Read();
            }

            byte[] binaryContent = reader.ReadContentAsBase64();
            string text          = Encoding.UTF8.GetString(binaryContent);

            Console.WriteLine(text);

            senderFactory.Close();
            receiverFactory.Close();
        }
Пример #13
0
        private Message ReceiveMessage(IInputChannel channel, bool commit)
        {
            Message message = null;

            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required))
            {
                bool messageDetected = false;
                if (this.Parameters.AsyncWaitForMessage)
                {
                    IAsyncResult result = channel.BeginWaitForMessage(this.Parameters.WaitForMessageTimeout, null, null);
                    messageDetected = channel.EndWaitForMessage(result);
                }
                else
                {
                    messageDetected = channel.WaitForMessage(this.Parameters.WaitForMessageTimeout);
                }

                if (this.Parameters.WaitForMessage)
                {
                    lock (this.Results)
                    {
                        this.Results.Add(String.Format("WaitForMessage returned {0}", messageDetected));
                    }
                }

                if (messageDetected)
                {
                    if (this.Parameters.AsyncReceive)
                    {
                        if (this.Parameters.TryReceive)
                        {
                            IAsyncResult result = channel.BeginTryReceive(this.Parameters.ReceiveTimeout, null, null);
                            bool         ret    = channel.EndTryReceive(result, out message);

                            lock (this.Results)
                            {
                                this.Results.Add(String.Format("TryReceive returned {0}", ret));
                            }
                        }
                        else
                        {
                            try
                            {
                                IAsyncResult result = channel.BeginReceive(this.Parameters.ReceiveTimeout, null, null);
                                message = channel.EndReceive(result);
                            }
                            catch (TimeoutException)
                            {
                                message = null;
                            }
                        }
                    }
                    else
                    {
                        if (this.Parameters.TryReceive)
                        {
                            bool ret = channel.TryReceive(this.Parameters.ReceiveTimeout, out message);

                            lock (this.Results)
                            {
                                this.Results.Add(String.Format("TryReceive returned {0}", ret));
                            }
                        }
                        else
                        {
                            try
                            {
                                message = channel.Receive(this.Parameters.ReceiveTimeout);
                            }
                            catch (TimeoutException)
                            {
                                message = null;
                            }
                        }
                    }
                }
                else
                {
                    if (this.Parameters.TryReceive)
                    {
                        bool ret = false;
                        if (this.Parameters.AsyncReceive)
                        {
                            IAsyncResult result = channel.BeginTryReceive(this.Parameters.ReceiveTimeout, null, null);
                            if (this.Parameters.TryReceiveNullIAsyncResult)
                            {
                                try
                                {
                                    channel.EndTryReceive(null, out message);
                                }
                                catch (Exception e)
                                {
                                    lock (this.Results)
                                    {
                                        this.Results.Add(String.Format("TryReceive threw {0}", e.GetType().Name));
                                    }
                                }
                            }

                            ret = channel.EndTryReceive(result, out message);
                        }
                        else
                        {
                            ret = channel.TryReceive(this.Parameters.ReceiveTimeout, out message);
                        }

                        lock (this.Results)
                        {
                            this.Results.Add(String.Format("TryReceive returned {0}", ret));
                            this.Results.Add(String.Format("Message was {0}", (message == null ? "null" : "not null")));
                        }
                    }

                    message = null;
                }

                if (commit && message != null)
                {
                    lock (this.Results)
                    {
                        this.Results.Add(String.Format("Received message with Action '{0}'", message.Headers.Action));
                    }

                    ts.Complete();
                }
                else
                {
                    Transaction.Current.Rollback();
                }
            }

            return(message);
        }
Пример #14
0
        private void sendButton_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            // Creating the Message
            TransmittedObject to = new TransmittedObject();

            to.str = "Hello";
            to.i   = 5;

            XmlSerializerWrapper wrapper =
                new XmlSerializerWrapper(typeof(TransmittedObject));

            Message m = Message.CreateMessage
                            (MessageVersion.Default, "urn:test", to, wrapper);

            // Creating the Channel
            string channelName = "EMailHelloWorld";

            string serverAddress = "*****@*****.**";
            string clientAddress = "*****@*****.**";

            WindowsMobileMailBinding   binding    = new WindowsMobileMailBinding();
            BindingParameterCollection parameters =
                new BindingParameterCollection();

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

            channelFactory.Open();

            // Opening the Channel
            IOutputChannel outChannel = channelFactory.CreateChannel(
                new EndpointAddress(MailUriHelper.Create
                                        (channelName, serverAddress)));

            outChannel.Open();

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

            // Listening for the response
            IChannelListener <IInputChannel> listner =
                binding.BuildChannelListener <IInputChannel>
                    (MailUriHelper.CreateUri(channelName, clientAddress),
                    parameters);

            listner.Open();

            IInputChannel inputChannel = listner.AcceptChannel();

            inputChannel.Open();

            Message reply = inputChannel.Receive();

            // Deserializing and using the Message
            TransmittedObject to1 =
                reply.GetBody <TransmittedObject>
                    (new XmlSerializerWrapper(typeof(TransmittedObject)));

            MessageBox.Show(to1.str + " " + to1.i.ToString());

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

            listner.Close();
            inputChannel.Close();
            binding.Close();

            Cursor.Current = Cursors.Default;
        }
Пример #15
0
        public void Run()
        {
            IRawBodyUtility bodyUtil = new RawEncoderUtility();

            IOutputChannel readyQueue = null;
            IOutputChannel doneQueue = null;
            UInt64 batchSize = (UInt64)opts.subTxSize;
            bool txPending = false;
            byte[] data = null;

            try
            {
                this.subscribeQueue = QueueChannelFactory.CreateReaderChannel(this.queue);
                readyQueue = QueueChannelFactory.CreateWriterChannel("", this.Fqn("sub_ready"));
                doneQueue = QueueChannelFactory.CreateWriterChannel("", this.Fqn("sub_done"));

                Message msg = bodyUtil.CreateMessage("ready");
                readyQueue.Send(msg, TimeSpan.MaxValue);
                msg.Close();

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                Console.WriteLine("receiving {0}", this.msgCount);
                UInt64 expect = 0;

                if (batchSize > 0)
                {
                    Transaction.Current = new CommittableTransaction();
                }

                for (UInt64 i = 0; i < this.msgCount; i++)
                {
                    msg = subscribeQueue.Receive(TimeSpan.MaxValue);

                    data = bodyUtil.GetBytes(msg, data);
                    msg.Close();
                    if (data.Length != this.msgSize)
                    {
                        throw new Exception("subscribe message size mismatch");
                    }

                    UInt64 n = GetSequenceNumber(data);
                    if (n != expect)
                    {
                        throw new Exception(String.Format("message sequence error. expected {0} got {1}", expect, n));
                    }
                    expect = n + 1;

                    if (batchSize > 0)
                    {
                        txPending = true;
                        if (((i + 1) % batchSize) == 0)
                        {
                            ((CommittableTransaction)Transaction.Current).Commit();
                            txPending = false;
                            Transaction.Current = new CommittableTransaction();
                        }
                    }
                }

                if (txPending)
                {
                    ((CommittableTransaction)Transaction.Current).Commit();
                }

                Transaction.Current = null;

                stopwatch.Stop();

                double mps = (msgCount / stopwatch.Elapsed.TotalSeconds);

                msg = bodyUtil.CreateMessage(String.Format("{0:0.##}", mps));
                doneQueue.Send(msg, TimeSpan.MaxValue);
                msg.Close();

                subscribeQueue.Close();
            }
            finally
            {
                Close((IChannel)doneQueue);
                Close((IChannel)this.subscribeQueue);
                Close(readyQueue);
            }
        }