当前位置:
首页 > Python基础教程 >
-
C#队列学习笔记:RabbitMQ实现客户端相互通讯
一、引言
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(); } /// <summary> /// 客户端 A /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button1_Click(object sender, EventArgs e) { ChatWith chatWith = new ChatWith(currentUserId: "UserA") { StartPosition = FormStartPosition.CenterScreen }; chatWith.Show(); } /// <summary> /// 客户端 B /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button2_Click(object sender, EventArgs e) { ChatWith chatWith = new ChatWith(currentUserId: "UserB") { StartPosition = FormStartPosition.CenterScreen }; chatWith.Show(); } /// <summary> /// 客户端 C /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button3_Click(object sender, EventArgs e) { ChatWith chatWith = new ChatWith(currentUserId: "UserC") { StartPosition = FormStartPosition.CenterScreen }; chatWith.Show(); } /// <summary> /// 客户端 D /// </summary> /// <param name="sender"></param> /// <param name="e"></param> 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>(T1 obj1); public delegate void ChatWithDelegate<T1, T2>(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"; /// <summary> /// 有参构造函数 /// </summary> /// <param name="currentUserId"></param> public ChatWith(string currentUserId) { InitializeComponent(); //在多线程程序中,新创建的线程不能访问UI线程创建的窗口控件。 //此时若想访问窗体的控件,可将窗体构造函数中的CheckForIllegalCrossThreadCalls设置为false。 //这时线程就能安全地访问窗体控件了。 CheckForIllegalCrossThreadCalls = false; CurrentUserId = currentUserId; } /// <summary> /// ShowMessage重载 /// </summary> /// <param name="msg"></param> 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); } } /// <summary> /// ShowMessage重载 /// </summary> /// <param name="toUserId"></param> /// <param name="msg"></param> 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); } } /// <summary> /// 绑定队列并订阅 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> 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<MessageBody>((message, info) => { if (message.Body.ToUserId == CurrentUserId) { ShowMessage(message.Body.FromUserId, message.Body.Message); } }); }); } else { ShowMessage("服务器连接失败。"); } } } /// <summary> /// 发送 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> 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>(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>(messageBody)); } } else { ShowMessage("发送消息失败。"); } } } catch (Exception ex) { ShowMessage(ex.Message); } } /// <summary> /// 关闭 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnClose_Click(object sender, EventArgs e) { Close(); } /// <summary> /// 窗体关闭事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ChatWith_FormClosed(object sender, FormClosedEventArgs e) { bus?.Dispose(); } }
2.5、运行结果
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比
一款纯 JS 实现的轻量化图片编辑器
关于开发 VS Code 插件遇到的 workbench.scm.
前端设计模式——观察者模式
前端设计模式——中介者模式
创建型-原型模式