微软专用消息队列msmq的简单使用

发送消息

        string path = "FormatName:Direct=TCP:192.168.5.52\\private$\\queue";
        //string path = ".\\Private$\\queue";//本地msmq
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="path"></param>
        public void SendMessage(string path)
        {
            try
            {
                MessageQueue myQueue = new MessageQueue(path);
                System.Messaging.Message mes = new System.Messaging.Message();
                mes.Body = textBox1.Text;
                mes.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                myQueue.Send(mes);
                MessageBox.Show("发送成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

接收消息

        string path = "FormatName:Direct=TCP:192.168.5.52\\private$\\queue";
        private void Form1_Load(object sender, EventArgs e)
        {
            MessageQueue myQueue = new MessageQueue(path);
            while (1 == 1)
            {
                try
                {
                    
                    System.Messaging.Message mes = myQueue.Receive();
                    mes.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                    MessageBox.Show(mes.Body.ToString());
                }
                catch (Exception e2)
                {
                    MessageBox.Show(e2.Message);
                }
            }
        }

 

posted @ 2019-03-05 13:26  木子zzgxl  阅读(175)  评论(0编辑  收藏  举报