一、引言
fanout类型的Exchange,路由规则非常简单:它会把所有发送到该Exchange的消息,路由到所有与它绑定的Queue中。假设有一个聊天室,各个客户端都订阅在同一fanout exchange type,那每个客户端发送出来的消息,所有的客户端都能收到,因为大家都订阅了。此时,只需要简单地限制一下,只有是与我有关的消息,才在聊天界面上显示。这样,即可达到相互通讯的效果。
二、示例
2.1、环境准备
本示例使用EasyNetQ来实现,请先在NuGet上安装。
2.2、实体类
新建一个实体类MessageBody:
public class MessageBody { public string FromUserId { get; set; } public string Message { get; set; } public string ToUserId { get; set; } }
2.3、主窗体
新建一个ChatMain窗体:
代码如下:
public partial class ChatMain : Form { public ChatMain() { InitializeComponent(); } ////// 客户端 A /// /// /// private void Button1_Click(object sender, EventArgs e) { ChatWith chatWith = new ChatWith(currentUserId: "UserA") { StartPosition = FormStartPosition.CenterScreen }; chatWith.Show(); } /// /// 客户端 B /// /// /// private void Button2_Click(object sender, EventArgs e) { ChatWith chatWith = new ChatWith(currentUserId: "UserB") { StartPosition = FormStartPosition.CenterScreen }; chatWith.Show(); } /// /// 客户端 C /// /// /// private void Button3_Click(object sender, EventArgs e) { ChatWith chatWith = new ChatWith(currentUserId: "UserC") { StartPosition = FormStartPosition.CenterScreen }; chatWith.Show(); } /// /// 客户端 D /// /// /// private void Button4_Click(object sender, EventArgs e) { ChatWith chatWith = new ChatWith(currentUserId: "UserD") { StartPosition = FormStartPosition.CenterScreen }; chatWith.Show(); } }
2.4、客户端窗体
新建一个ChatWith窗体:
代码如下:
public partial class ChatWith : Form { public delegate void ChatWithDelegate(); public delegate void ChatWithDelegate(T1 obj1); public delegate void ChatWithDelegate (T1 obj1, T2 obj2); public string CurrentUserId { get; } private IBus bus; public const string ConnStringMQ = "host=192.168.2.242:5672,192.168.2.165:5672;virtualHost=/;username=hello;password=world"; public const string FanoutExchange = "fanoutEC"; /// /// 有参构造函数 /// /// public ChatWith(string currentUserId) { InitializeComponent(); //在多线程程序中,新创建的线程不能访问UI线程创建的窗口控件。 //此时若想访问窗体的控件,可将窗体构造函数中的CheckForIllegalCrossThreadCalls设置为false。 //这时线程就能安全地访问窗体控件了。 CheckForIllegalCrossThreadCalls = false; CurrentUserId = currentUserId; } /// /// ShowMessage重载 /// /// private void ShowMessage(string msg) { if (InvokeRequired)//InvokeRequired:当前线程不是创建控件的线程时为true { BeginInvoke(new ChatWithDelegate<string>(ShowMessage), msg); } else { ListViewItem item = new ListViewItem(new string[] { DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msg }); lvwReceiveMsg.Items.Insert(0, item); } } /// /// ShowMessage重载 /// /// /// private void ShowMessage(string toUserId, string msg) { if (InvokeRequired) { BeginInvoke(new ChatWithDelegate<string, string>(ShowMessage), toUserId, msg); } else { ListViewItem item = new ListViewItem(new string[] { DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), toUserId, msg }); lvwReceiveMsg.Items.Insert(0, item); } } /// /// 绑定队列并订阅 /// /// /// private void ChatWith_Load(object sender, EventArgs e) { cmbOnLine.SelectedIndex = 0; Text = Text + $"[{CurrentUserId}]"; //这里不能使用using,否则订阅者立即就释放了,订阅不到消息。 bus = RabbitHutch.CreateBus(ConnStringMQ); { if (bus.IsConnected) { var exchange = bus.Advanced.ExchangeDeclare(name: FanoutExchange, type: ExchangeType.Fanout); var queue = bus.Advanced.QueueDeclare(name: $"{FanoutExchange}_queue_{CurrentUserId}"); bus.Advanced.Bind(exchange: exchange, queue: queue, routingKey: ""); bus.Advanced.Consume(queue, registration => { registration.Add ((message, info) => { if (message.Body.ToUserId == CurrentUserId) { ShowMessage(message.Body.FromUserId, message.Body.Message); } }); }); } else { ShowMessage("服务器连接失败。"); } } } /// /// 发送 /// /// /// private void btnSend_Click(object sender, EventArgs e) { try { using (var bus = RabbitHutch.CreateBus(ConnStringMQ)) { if (bus.IsConnected) { if (cmbOnLine.Text == "*")//群发 { foreach (var item in cmbOnLine.Items.Cast<string>().Where(s => s != "*" && s != CurrentUserId)) { var exchange = bus.Advanced.ExchangeDeclare(name: FanoutExchange, type: ExchangeType.Fanout); var messageBody = new MessageBody { FromUserId = CurrentUserId, Message = txtSendMsg.Text, ToUserId = item }; bus.Advanced.Publish(exchange: exchange, routingKey: "", mandatory: false, message: new Message (messageBody)); } } else//私聊 { var exchange = bus.Advanced.ExchangeDeclare(name: FanoutExchange, type: ExchangeType.Fanout); var messageBody = new MessageBody { FromUserId = CurrentUserId, Message = txtSendMsg.Text, ToUserId = cmbOnLine.Text }; bus.Advanced.Publish(exchange: exchange, routingKey: "", mandatory: false, message: new Message (messageBody)); } } else { ShowMessage("发送消息失败。"); } } } catch (Exception ex) { ShowMessage(ex.Message); } } /// /// 关闭 /// /// /// private void btnClose_Click(object sender, EventArgs e) { Close(); } /// /// 窗体关闭事件 /// /// /// private void ChatWith_FormClosed(object sender, FormClosedEventArgs e) { bus?.Dispose(); } }