如何给MSMQ发送Message (local computer | remote computer)

 

    利用 MSMQMicrosoft Message Queue),应用程序开发人员可以通过发送和接收消息方便地与应用程序进行快速可靠的通信。消息处理为您提供了有保障的消息传递和执行许多业务处理的可靠的防故障方法。
MSMQXML Web Services.Net Remoting一样,是一种分布式开发技术。但是在使用XML Web Services.Net Remoting组件时,Client端需要和Server端实时交换信息,Server需要保持联机。MSMQ则可以在Server离线的情况下工作,将Message临时保存在Client端的消息队列中,以后联机时再发送到Server端处理。
显然,MSMQ不适合于Client需要Server端及时响应的这种情况,MSMQ以异步的方式和Server端交互,不用担心等待Server端的长时间处理过程。
 
    虽然XML Web Services.Net Remoting都提供了利用 MSMQMicrosoft Message Queue),应用程序开发人员可以通过发送和接收消息方便地与应用程序进行快速可靠的通信。消息处理为您提供了有保障的消息传递和执行许多业务处理的可靠的防故障方法。
MSMQXML Web Services.Net Remoting一样,是一种分布式开发技术。但是在使用XML Web Services.Net Remoting组件时,Client端需要和Server端实时交换信息,Server需要保持联机。MSMQ则可以在Server离线的情况下工作,将Message临时保存在Client端的消息队列中,以后联机时再发送到Server端处理。
显然,MSMQ不适合于Client需要Server端及时响应的这种情况,MSMQ以异步的方式和Server端交互,不用担心等待Server端的长时间处理过程。
 
虽然XML Web Services.Net Remoting都提供了

 用户创建的队列可能是以下任何一种队列:
public queue:如果该MSMQ Server已经加入到了某个域,则其可以接收public queue,否则不能接收消息到public queue.

private queue:
 
系统生成的队列一般分为以下几类:
日记队列可选地存储发送消息的副本和从队列中移除的消息副本。每个消息队列客户端上的单个日记队列存储从该计算机发送的消息副本。在服务器上为每个队列创建了一个单独的日记队列。此日记跟踪从该队列中移除的消息。
死信队列存储无法传递或已过期的消息的副本。如果过期或无法传递的消息是事务性消息,则被存储在一种特殊的死信队列中,称为事务性死信队列。死信存储在过期消息所在的计算机上。有关超时期限和过期消息的更多信息,请参见默认消息属性。
报告队列包含指示消息到达目标所经过的路由的消息,还可以包含测试消息。每台计算机上只能有一个报告队列。
专用系统队列是一系列存储系统执行消息处理操作所需的管理和通知消息的专用队列。
在应用程序中进行的大多数工作都涉及访问公共队列及其消息。但是,根据应用程序的日记记录、确认和其他特殊处理需要,在日常操作中很可能要使用几种不同的系统队列。
 
3. 同步和异步通信(Synchronous VS. Asynchronous Communication
队列通信天生就是异步的,因为将消息发送到队列和从队列中接收消息是在不同的进程中完成的。另外,可以异步执行接收操作,因为要接收消息的人可以对任何给定的队列调用 BeginReceive 方法,然后立即继续其他任务而不用等待答复。这与人们所了解的同步通信截然不同。
 
在同步通信中,请求的发送方在执行其他任务前,必须等待来自预定接收方的响应。发送方等待的时间完全取决于接收方处理请求和发送响应所用的时间。
 
4. 同消息队列交互(Interacting with Message Queues
消息处理和消息为基于服务器的应用程序组件之间的进程间通信提供了强大灵活的机制。同组件间的直接调用相比,它们具有若干优点,其中包括:

·         稳定性 — 组件失败对消息的影响程度远远小于组件间的直接调用,因为消息存储在队列中并一直留在那里,直到被适当地处理。消息处理同事务处理相似,因为消息处理是有保证的。

·         消息优先级 — 更紧急或更重要的消息可在相对不重要的消息之前接收,因此可以为关键的应用程序保证足够的响应时间。

·         脱机能力 — 发送消息时,它们可被发送到临时队列中并一直留在那里,直到被成功地传递。当因任何原因对所需队列的访问不可用时,用户可以继续执行操作。同时,其他操作可以继续进行,如同消息已经得到了处理一样,这是因为网络连接恢复时消息传递是有保证的。

·         事务性消息处理 — 将多个相关消息耦合为单个事务,确保消息按顺序传递、只传递一次并且可以从它们的目标队列中被成功地检索。如果出现任何错误,将取消整个事务。

·         安全性 — MessageQueue 组件基于的消息队列技术使用 Windows 安全来保护访问控制,提供审核,并对组件发送和接收的消息进行加密和验证。


 
5. 
    1.编写代码-简单演示MSMQ对象
    MessageQueue 类是消息队列周围的包装。MessageQueue 类提供对消息队列队列的引用。可以在 MessageQueue 构造函数中指定一个连接到现有资源的路径,或者可在服务器上创建新队列。在调用 SendPeek Receive 之前,必须将 MessageQueue 类的新实例与某个现有队列关联。 
MessageQueue 支持两种类型的消息检索:同步和异步。同步的 Peek Receive 方法使进程线程用指定的间隔时间等待新消息到达队列。异步的 BeginPeek BeginReceive 方法允许主应用程序任务在消息到达队列之前,在单独的线程中继续执行。这些方法通过使用回调对象和状态对象进行工作,以便在线程之间进行信息通讯。
#define Debug
//send message

private void btnSendMessage_Click(object sender, System.EventArgs e)
{
      // Open queue
       System.Messaging.MessageQueue queue = new  System.Messaging.MessageQueue(@"FormatName:Direct=Tcp:192.168.1.254\Private$\msmqdemo"); 

//MSMQ private remote server :192.168.1.254

//if send/recipent message from local, the string shoule be: @".\private\msmqdemo");
       // Create message
       System.Messaging.Message message = new System.Messaging.Message();
       message.Body = message.Text.Trim();
       message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] {typeof(string)});
       // Put message into queue
     queue.sendMessage(message); 
    
}
 
//case 1:receive message synchrousely 
private void btnReceiveMessage_Click(object sender, System.EventArgs e)
{
       // Open queue
       System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(@"FormatName:Direct=Tcp:192.168.1.254\Private$\msmqdemo"");
 
       // Receive message, 同步的Receive方法阻塞当前执行线程,直到一个message可以得到
       System.Messaging.Message message = queue. Receive();
       message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] {typeof(string)})

       txtReceiveMessage.Text = message.Body.ToString();
}

//case 2:receive message asynchronousely
private void btnReceiveAsyncronousely_Click(obect sender,System.EventArgs e)
{
// Open queue
       System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue@"FormatName:Direct=Tcp:192.168.1.254\Private$\msmqdemo"");
  queue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);
   queue.BeginReceive();

}

 public void queue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
        {
            MessageQueue mq = (MessageQueue)sender;
            System.Messaging.Message m = mq.EndReceive(e.AsyncResult);
            m.Formatter=new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string)});
            //e_RM.Text = m.Body.ToString();
#if Debug
            MessageBox.Show("received message asynchrousely. the message's body is "+m.Body.ToString());
#endif
            System.IO.StreamWriter sw=new System.IO.StreamWriter("message.txt");
            sw.Write(m.Body.ToString());
            sw.Close();
        }

 
case 3:send/recipient Transactianal Message

 

  private void button4_Click(object sender, EventArgs e)
        {
            System.Messaging.MessageQueue mq= new MessageQueue(@"FormatName:Direct=Tcp:192.168.1.254\Private$\msmqdemo",true);                       
            System.Messaging.MessageQueueTransaction transaction = new MessageQueueTransaction();
                try
                {
                    System.Messaging.Message m = new System.Messaging.Message();
                    m.Label = tb_ml1.Text;
                    m.Body = tb_tm1.Text;
                    m.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });

                    System.Messaging.Message m1 = new System.Messaging.Message();
                    m1.Label = tb_ml2.Text;
                    m1.Body = tb_tm2.Text;
                    m1.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });

                    System.Messaging.Message m2 = new System.Messaging.Message();
                    m2.Label = tb_ml3.Text;
                    m2.Body = tb_tm3.Text;
                    m2.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });

                    transaction.Begin();
                    mq.Send(m, transaction);
                    mq.Send(m1, transaction);
                    mq.Send(m2, transaction);
                    transaction.Commit();
                    MessageBox.Show("transactional message sent successfully!");
                }
                catch (Exception ex)
                {
                    transaction.Abort();
                    MessageBox.Show(ex.Message,"Exception",MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

        
          

        }


case 4: send/recipient object message 

 public class Employer
    {
        private string _acountID;
        private string _name;
        private string _alias;

        public Employer() { }

        public Employer(string acountId, string name, string alias)
        {
            this._acountID = acountId;
            this._name = name;
            this._alias = alias;
        }

        public string AcountID
        {
            get
            {
                return _acountID;
            }
            set
            {
                _acountID = value;
            }
        }

        public string Name
        {
            get
            {
                return _name;
            }

            set
            {
                _name = value;
            }
        }

        public string Alias
        {
            get
            {
                return _alias;
            }
            set
            {
                _alias = value;
            }
        }
    }

 

//send object message

 private void SendObject_Click(object sender, EventArgs e)
        {
            //blank the received area content
            e_ROM.Text = "";
            Employer obj_Employer = new Employer();
            obj_Employer.AcountID = tb_acountid.Text.Trim();
            obj_Employer.Name = tb_name.Text.Trim();
            obj_Employer.Alias = tb_alias.Text.Trim();

            System.Messaging.MessageQueue queue= new MessageQueue(@"FormatName:Direct=Tcp:192.168.1.254\Private$\msmqdemo");
          
    if (this.get_Formatter() == Format_Type.XML)
                queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(MSMQDemo.Employer) });
            else
                queue.Formatter = new BinaryMessageFormatter();

            System.Messaging.Message obj_MSG = new System.Messaging.Message(obj_Employer);
                     
            queue.Send(obj_MSG);

            MessageBox.Show("object message sent successfully!","system info",MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

 

//recipient object message

 private void RecipientObject_Click(object sender, EventArgs e)
        {           
            System.Messaging.MessageQueue queue= new MessageQueue(@"FormatName:Direct=Tcp:192.168.1.254\Private$\msmqdemo");

            if (this.Format == Format_Type.XML)
                queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(MSMQDemo.Employer) });
            else
                queue.Formatter = new BinaryMessageFormatter();
            try
            {              
                System.Messaging.Message msg = queue.Receive();
                Employer receive_Em = (Employer)msg.Body;
               
                e_ROM.Text = "";
                e_ROM.Text += " the received result is following:\n";
                e_ROM.Text += "==================================\n";
                e_ROM.Text += "AccountID" + receive_Em.AcountID + "\n";
                e_ROM.Text += "Name " + receive_Em.Name + "\n";
                e_ROM.Text += "Alias" + receive_Em.Alias + "\n";
            }
            catch (Exception E)
            {
                MessageBox.Show(E.Message.ToString(), "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

 

 case 5:send/recipient BigObject message, for example:file, image, doc and etc.

the following sample give us a exmaple about how to send / recipient message that contains image

 private void bt_sendmessage_Click(object sender, EventArgs e)
        {
            try
            {
                System.Drawing.Image myImage = Bitmap.FromFile(tb_filename.Text);
                //System.IO.FileStream myImage = new FileStream(tb_filename.Text,FileMode.Open);
                MessageQueue queue = new MessageQueue(@"FormatName:Direct=Tcp:192.168.1.254\Private$\msmqdemo");
               
                System.Messaging.Message mymessage = new System.Messaging.Message(myImage, new BinaryMessageFormatter());
                queue.Send(mymessage);
            }
            catch (MessageQueueException me)
            {
                MessageBox.Show(me.Message.ToString());
            }
        }

 

 private void bt_receivemessage_Click(object sender, EventArgs e)
        {
            MessageQueue queue = new MessageQueue(@"FormatName:Direct=Tcp:192.168.1.254\Private$\msmqdemo");
            queue.Formatter = new BinaryMessageFormatter();
            System.Messaging.Message message = queue.Receive();
            Bitmap myImage = (Bitmap)message.Body;
            //FileStream myImage = (FileStream)message.Body;
            string savefilename;
            SaveFileDialog sf = new SaveFileDialog();
            sf.Filter = "Image file(*.gif;*.jpg;*.bmp)|*.gif;*.jpg;*.bmp;|office file|*.docx;*.exl;*.ppt|All Files(*.*)|*.*";
            if (sf.ShowDialog() == DialogResult.OK)
                 myImage.Save(sf.FileName, System.Drawing.Imaging.ImageFormat.Gif);
                //myImage.
                //;
        }

posted on 2008-03-31 09:31  飞天舞者  阅读(1197)  评论(0编辑  收藏  举报

导航

For more information about me, feel free email to me winston.he@hotmail.com