代码改变世界

MSMQ小Demo

2015-05-14 22:07  Yang-Onion  阅读(364)  评论(0编辑  收藏  举报

Demo基于http://www.cnblogs.com/zhili/p/MSMQ.html

Server代码:

using System.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace MSMQServer
{
    class Program
    {
        static void Main(string[] args)
        {
            const string messageQueuePath = @".\Private$\MyPrivateMessageQueue";
            if (!MessageQueue.Exists(messageQueuePath))
            {
                using (MessageQueue mq = MessageQueue.Create(messageQueuePath))
                {
                    mq.Label = "";
                    Console.WriteLine("已创建一个私有信息队列。");
                    Console.WriteLine("消息队列名称:{0}",mq.QueueName);
                    Console.WriteLine("消息队列路径:{0}",mq.Path);
                    mq.Send("My First MessageQueue Message ");
                }
            }


            if (MessageQueue.Exists(messageQueuePath))
            {
                using (MessageQueue mq = new MessageQueue(messageQueuePath))
                {
                    Console.WriteLine("消息队列名称:{0}", mq.QueueName);
                    Console.WriteLine("消息队列路径:{0}", mq.Path);
                    mq.Send("My Second MessageQueue Message !");
                }
               
            }

            Console.ReadKey();
        }
    }
}

Client代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace MSMQClient
{
    class Program
    {
        static void Main(string[] args)
        {
            const string messageQueuePath = @".\Private$\MyPrivateMessageQueue";
            if (MessageQueue.Exists(messageQueuePath))
            {
                using (MessageQueue mq=new MessageQueue(messageQueuePath))
                {
                    mq.Formatter=new XmlMessageFormatter(new string[]{"System.String"});
                    int i = 0;
                    foreach (var message in mq.GetAllMessages())
                    {
                        Console.WriteLine("My  MessageQueue Message {0} :{1}", i, message.Body);
                        i++;
                    }

                    var msg = mq.Receive();
                    Console.WriteLine("My First Receive MessageQueue Message  Is :{0} ", msg.Body);
                }
            }

            Console.ReadKey();
        }
    }
}

 

XMind

练习代码

 

home page tracking
NutriSystem Diet