c#中使用MSMQ

c#中使用MSMQ,第1张

MSMQ是微软自带的消息队列,可以当作通信工具使用,现在用它建立一个聊天的功能,一个服务端,多个客户端进行实时聊天系统。使用它之前,必须先进行配置。

1.在Windows功能中先安装,如下图所示

2.在计算机管理中,就会看到消息队列

3.服务端代码,创建一个MQ

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ServerMSMQ
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            //本地发送MessageQueue mq = new MessageQueue(@".\Private$\susuMSMQ");
            //tcp发送new MessageQueue(@"FormatName:Direct=tcp:localhoost\Private$\kkkMQ");
            //局域网发送new MessageQueue(@"FormatName:Direct=http://localhost/msmq/Private$/kkkMQ");
            //局域网发送new MessageQueue(@"FormatName:Direct=http://192.168.1.100/msmq/Private$/kkkMQ");
            //使用内网穿透域名发送new MessageQueue(@"FormatName:Direct=http://susumsmq.frpgz1.idcfengye.com/msmq/Private$/kkkMQ");

            //MQ的名字,也可以使用上面的方法建立
            string mqName = $".\private$\{textBox1.Text.Trim()}";
            //string mqName = @"FormatName:Direct=TCP:192.168.1.101\Private$\mqtest";

            //如果不存在mqName消息队列,则创建该mqName消息队列  
            if (MessageQueue.Exists(mqName))
            {
                MessageBox.Show("该消息队列已经存在!");
            }
            else
            {
                MessageQueue.Create(mqName);

                MessageQueue queue = new MessageQueue(mqName);
                queue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl, AccessControlEntryType.Allow);    //加权限
                queue.SetPermissions("ANONYMOUS LOGON", MessageQueueAccessRights.FullControl, AccessControlEntryType.Allow);
                MessageBox.Show("该消息队列创建成功!");
            }
        }
    }
}

 4.运行代码后,创建成功

5.客户端界面

6.客户端代码

设计界面代码


namespace clientMSMQ
{
    partial class Form1
    {
        /// 
        /// 必需的设计器变量。
        /// 
        private System.ComponentModel.IContainer components = null;

        /// 
        /// 清理所有正在使用的资源。
        /// 
        /// 如果应释放托管资源,为 true;否则为 false。
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// 
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// 
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.label1 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.listBox1 = new System.Windows.Forms.ListBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.button2 = new System.Windows.Forms.Button();
            this.textBox3 = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.textBox4 = new System.Windows.Forms.TextBox();
            this.label4 = new System.Windows.Forms.Label();
            this.textBox5 = new System.Windows.Forms.TextBox();
            this.label5 = new System.Windows.Forms.Label();
            this.button3 = new System.Windows.Forms.Button();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.button4 = new System.Windows.Forms.Button();
            this.button5 = new System.Windows.Forms.Button();
            this.button6 = new System.Windows.Forms.Button();
            this.button7 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(142, 161);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(77, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "接收人姓名:";
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(225, 158);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(100, 21);
            this.textBox1.TabIndex = 1;
            this.textBox1.Text = "张三";
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(349, 102);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 2;
            this.button1.Text = "接收消息";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // listBox1
            // 
            this.listBox1.FormattingEnabled = true;
            this.listBox1.ItemHeight = 12;
            this.listBox1.Location = new System.Drawing.Point(132, 243);
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(294, 232);
            this.listBox1.TabIndex = 3;
            // 
            // textBox2
            // 
            this.textBox2.Location = new System.Drawing.Point(225, 205);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(100, 21);
            this.textBox2.TabIndex = 5;
            this.textBox2.Text = "123";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(149, 208);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(41, 12);
            this.label2.TabIndex = 4;
            this.label2.Text = "内容:";
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(349, 203);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 6;
            this.button2.Text = "发送";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // textBox3
            // 
            this.textBox3.Location = new System.Drawing.Point(225, 104);
            this.textBox3.Name = "textBox3";
            this.textBox3.Size = new System.Drawing.Size(100, 21);
            this.textBox3.TabIndex = 7;
            this.textBox3.Text = "李四";
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(149, 107);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(65, 12);
            this.label3.TabIndex = 8;
            this.label3.Text = "本人姓名:";
            // 
            // textBox4
            // 
            this.textBox4.Location = new System.Drawing.Point(225, 12);
            this.textBox4.Name = "textBox4";
            this.textBox4.Size = new System.Drawing.Size(100, 21);
            this.textBox4.TabIndex = 10;
            this.textBox4.Text = "mqtest";
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(130, 15);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(89, 12);
            this.label4.TabIndex = 9;
            this.label4.Text = "消息队列名称:";
            // 
            // textBox5
            // 
            this.textBox5.Location = new System.Drawing.Point(225, 38);
            this.textBox5.Name = "textBox5";
            this.textBox5.Size = new System.Drawing.Size(100, 21);
            this.textBox5.TabIndex = 14;
            this.textBox5.Text = "192.168.1.101";
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(137, 38);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(53, 12);
            this.label5.TabIndex = 13;
            this.label5.Text = "IP地址:";
            // 
            // button3
            // 
            this.button3.Location = new System.Drawing.Point(484, 335);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(109, 23);
            this.button3.TabIndex = 15;
            this.button3.Text = "开始自动接收消息";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.button3_Click);
            // 
            // timer1
            // 
            this.timer1.Interval = 1000;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            // 
            // button4
            // 
            this.button4.Location = new System.Drawing.Point(518, 223);
            this.button4.Name = "button4";
            this.button4.Size = new System.Drawing.Size(75, 23);
            this.button4.TabIndex = 16;
            this.button4.Text = "开始发送";
            this.button4.UseVisualStyleBackColor = true;
            this.button4.Click += new System.EventHandler(this.button4_Click);
            // 
            // button5
            // 
            this.button5.Location = new System.Drawing.Point(617, 223);
            this.button5.Name = "button5";
            this.button5.Size = new System.Drawing.Size(75, 23);
            this.button5.TabIndex = 17;
            this.button5.Text = "停止发送";
            this.button5.UseVisualStyleBackColor = true;
            this.button5.Click += new System.EventHandler(this.button5_Click);
            // 
            // button6
            // 
            this.button6.Location = new System.Drawing.Point(617, 335);
            this.button6.Name = "button6";
            this.button6.Size = new System.Drawing.Size(122, 23);
            this.button6.TabIndex = 18;
            this.button6.Text = "停止自动接收消息";
            this.button6.UseVisualStyleBackColor = true;
            this.button6.Click += new System.EventHandler(this.button6_Click);
            // 
            // button7
            // 
            this.button7.Location = new System.Drawing.Point(370, 38);
            this.button7.Name = "button7";
            this.button7.Size = new System.Drawing.Size(75, 23);
            this.button7.TabIndex = 19;
            this.button7.Text = "连接";
            this.button7.UseVisualStyleBackColor = true;
            this.button7.Click += new System.EventHandler(this.button7_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(800, 506);
            this.Controls.Add(this.button7);
            this.Controls.Add(this.button6);
            this.Controls.Add(this.button5);
            this.Controls.Add(this.button4);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.textBox5);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.textBox4);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.textBox3);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.listBox1);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.label1);
            this.Name = "Form1";
            this.Text = "clientMSMQ";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.ListBox listBox1;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.TextBox textBox3;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.TextBox textBox4;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.TextBox textBox5;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.Timer timer1;
        private System.Windows.Forms.Button button4;
        private System.Windows.Forms.Button button5;
        private System.Windows.Forms.Button button6;
        private System.Windows.Forms.Button button7;
    }
}

后台界面代码

using System;
using System.Messaging;
using System.Threading;
using System.Windows.Forms;
using Message = System.Messaging.Message;

namespace clientMSMQ
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string ekQ = string.Empty;
        MessageQueue myQueue = null;


        /// 
        /// 接收
        /// 
        /// 
        /// 
        private void button1_Click(object sender, EventArgs e)
        {
            //string ekQ = $@"FormatName:Direct=TCP:{textBox5.Text.Trim()}\Private$\{textBox4.Text.Trim()}";
            try
            {


                // 创建消息队列对象
                using (myQueue)
                {
                    //mq.BeginReceive();
                    // 设置消息队列的格式化器

                    //Message msg1 = mq.Receive();
                    // msg1.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });
                    // string s = msg1.Body.ToString();

                    myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });//mq.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
                    foreach (Message msg in myQueue.GetAllMessages())
                    {
                        listBox1.Items.Add(msg.Body);
                        myQueue.Receive();//接收完成后,就销毁了
                    }

                    // 获得消息队列中第一条可用消息
                    //Message firstmsg = mq.Receive();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex + ex.Message);
            }
            
        }

        /// 
        /// 发送
        /// 
        /// 
        /// 
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                myQueue.Send($"{textBox3.Text}|{textBox1.Text}|{textBox2.Text}");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }


        //通知一个或多个正在等待的线程已发生事件
        static ManualResetEvent signal = new ManualResetEvent(false);
        /// 
        /// 异步接收消息
        /// 
        private void AsyncReceiveMessage()
        {
            //这里使用了委托,当接收消息完成的时候就执行MyReceiveCompleted方法
            myQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(MyReceiveCompleted);
            myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });

            myQueue.BeginReceive();//启动一个没有超时时限的异步 *** 作
            bool b = signal.WaitOne();
        }
        private void MyReceiveCompleted(Object source, ReceiveCompletedEventArgs asyncResult)
        {
            try
            {
                MessageQueue mq = (MessageQueue)source;
                //完成指定的异步接收 *** 作
                Message message = mq.EndReceive(asyncResult.AsyncResult);
                signal.Set();
                Invoke(new Action(() => listBox1.Items.Add(message.Body)));
                mq.BeginReceive();
            }
            catch (MessageQueueException)
            {

            }
        }


        private void button3_Click(object sender, EventArgs e)
        {
            AsyncReceiveMessage();
        }

        int i = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            myQueue.Send($"123||" + i++);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            timer1.Start();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            timer1.Stop();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            myQueue.Close();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            ekQ = $@"FormatName:Direct=TCP:{textBox5.Text.Trim()}\Private$\{textBox4.Text.Trim()}";
            myQueue = new MessageQueue(ekQ);
            MessageBox.Show("连接成功!");
        }
    }
}

 7.李四给张三发送消息

 8.张三收到消息后,再给李四发送消息

9.如果进行实时通信的话,加一个线程。这里可以用发送的文字进行区分,双方根据指定的消息进行接受。

 10.效果

 

下面是2个配置文件

如果出现不能访问的话,加注册表。reg文件是:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSMQ\Parameters\security]
"LqsUpdatedSD"=dword:00000001
"AllowNonauthenticatedRpc"=dword:00000001
"NewRemoteReadServerDenyWorkgroupClient"=dword:00000001

 安装MSMQ的bat。bat文件是:

start /w pkgmgr /iu:MSMQ-Container;MSMQ-Server;MSMQ-Triggers;MSMQ-ADIntegration;MSMQ-HTTP;MSMQ-Multicast;MSMQ-DCOMProxy

注意:MSQM的安装,配置总有点问题,偶尔会出现有些电脑可以,有些电脑不可以,很鸡肋,能不用的话,尽量不要使用,坑非常的多,而且MessageQueue类提供的有些方法还不能跨局域网。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/742221.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存