创建Service Bus能够參照:

https://azure.microsoft.com/en-gb/documentation/articles/service-bus-dotnet-how-to-use-topics-subscriptions/

Azure Service Bus做广播和消息通知功能非常合适,而且能够订阅不同的Topic(不同的消息类型或不同的聊天室)。

1. 首先须要安装Azure Service Bus的nuget package:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGFuX2xpYW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

2. 建议安装Azure Service Explorer来查看Service bus中创建的Q或者Topic(本文主要介绍Topic)

https://code.msdn.microsoft.com/windowsazure/Service-Bus-Explorer-f2abca5a

非常好用。而且开源,能够学习。

3. 实现过程

3.1 首先创建1个Winform程序,拖两个button和两个Textbox。界面例如以下:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGFuX2xpYW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

3.2 创建1个类,叫ChatClient:

public class ChatClient
{
private string ConnStr
{
get
{
return CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
}
} private const string topicName = "TestTopic";
public OnMsgRecieved OnMsgRecieved; public void Subscribe(string subscriber)
{
var td = new TopicDescription(topicName)
{
MaxSizeInMegabytes = 5120,
DefaultMessageTimeToLive = new TimeSpan(0, 1, 0)
}; // Create a new Topic with custom settings
string connectionString =
CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); var namespaceManager =
NamespaceManager.CreateFromConnectionString(connectionString); if (!namespaceManager.TopicExists(topicName))
{
namespaceManager.CreateTopic(td);
} if (!namespaceManager.SubscriptionExists(topicName, subscriber))
{
namespaceManager.CreateSubscription(topicName, subscriber);
} SubscriptionClient Client = SubscriptionClient.CreateFromConnectionString
(ConnStr, topicName, subscriber, ReceiveMode.PeekLock); // Configure the callback options
OnMessageOptions options = new OnMessageOptions();
options.AutoComplete = false;
options.AutoRenewTimeout = TimeSpan.FromMinutes(1); Task.Run(() =>
{
Client.OnMessage((message) =>
{
try
{
// Process message from subscription
OnMsgRecieved(string.Format("{0}:{1}",
message.Properties["name"], message.GetBody<string>()));
}
catch (Exception)
{
// Indicates a problem, unlock message in subscription
message.Abandon();
}
}, options);
}); } private TopicClient _topicClient; public TopicClient TopicClient
{
get
{
if (_topicClient == null)
{
_topicClient = TopicClient.CreateFromConnectionString(ConnStr, topicName);
} return _topicClient;
}
} public void SendMsg(string name, string msg)
{
var message = new BrokeredMessage(msg);
message.Properties["name"] = name;
TopicClient.Send(message);
} }

1. 代码包括了Subscribe和SendMsg两个方法,注意name用于标识client的。假设两个client给一样的名字,仅仅有client1个client能收到消息。

2. 我Hard Code了Topic名称,假设须要实现多种消息广播。给不同的名字就能够了

3. 这行代码:

SubscriptionClient Client = SubscriptionClient.CreateFromConnectionString
(ConnStr, topicName, subscriber, ReceiveMode.PeekLock);

中的ReceiveMode包括两种:PeekLock和ReceiveAndDelete ,前者加锁拿消息放回,后者拿消息并删除。

4. TopicClient不必每次都创建。是支持多线程环境的。

5. 

var td = new TopicDescription(topicName)
{
MaxSizeInMegabytes = 5120,
DefaultMessageTimeToLive = new TimeSpan(0, 1, 0)
};

这里设置了消息的最大长度和默认生命周期,可依据场景进行配置。

Winform的UI逻辑代码相对简单:

 public partial class Form1 : Form
{
ChatClient cc = new ChatClient(); public Form1()
{
InitializeComponent();
cc.OnMsgRecieved = (msg) =>
{
SetText(msg);
};
} private void btnSend_Click(object sender, EventArgs e)
{
cc.SendMsg(txtName.Text, txtMsg.Text);
} delegate void SetTextCallback(string text); private void SetText(string text)
{
if (txtResult.InvokeRequired)
{
var d = new SetTextCallback(SetText);
Invoke(d, new object[] { text });
}
else
{
txtResult.Text += "\r\n" + text;
}
} private void btnSaveName_Click(object sender, EventArgs e)
{
cc.Subscribe(txtName.Text);
}
}

逻辑非常easy,点击SaveName。又一次订阅。点Send按钮,发送消息。

须要注意的就是跨线程訪问UI控件,这里你须要一个delegate。

实现截图:

最新文章

  1. 三种POST和GET的提交方式
  2. sourceTree忽略文件
  3. NOIP 考前 数论复习
  4. jQuery判断一个字符串中是否包含一个字符串(一)
  5. angularjs(一)基础概念
  6. python--基础学习(四)自然字符串、重复字符串、子字符串
  7. Ubuntu下安装IDA pro
  8. centos7时间同步和时区设置
  9. hdu1950 最长上升子序列nlogn
  10. [51NOD1105]第k大的数(二分答案)
  11. HttpClient4.4 进行Http连接通讯
  12. 启动Tomcat提示:指定的服务未安装
  13. 【转】 文档与笔记利器 reStructuredText 和 Sphinx
  14. vscode 前端插件推荐
  15. 查找datatable 中的重复记录(只查询一个字段)
  16. python3 基础语法(一)
  17. sqlserver可将字符转成数字再进行sum,如果varchar类型中存放的都是数字
  18. 内核里面writel(readl)是如何实现的
  19. Sublime 插件路径
  20. cocos2d-x系列笔记技巧篇(2)---关于CREATE_FUNC宏的用法

热门文章

  1. 安装visual studio 2013【转】
  2. AdaBoostClassifier实战
  3. JS——BOM操作(基本用法与实现:open()、close()、scrollTop等了解)
  4. eclipse中文汉字看不清或过小的问题解决方法!!
  5. angular4搭建博客(一)
  6. Android Fragment 初步解析
  7. MSSQL_20160719_在作业步骤中使用sp_send_dbmail遇到的问题
  8. deeplearning4j – 分布式DL开源项目
  9. C语言break/continue/exit/return的功能区别
  10. CorelDRAW X8超低价优惠啦,你却还在用CDR X4破解?!