《Windows Azure Platform 系列文章目录

  项目文件,请在这里下载

  在笔者之前的文章中Windows Azure Service Bus (1) 基础

  介绍了Service Bus支持主题(Topic)。如下图:

  

  当2个客户端同时订阅了相同的主题(Topic)。当向这个Topic发送消息的时候,2个客户端会同时收到该消息。

  笔者模拟一个在线聊天室的场景:

  1.创建一个Windows Console命令行项目,编写相应的代码

  2.运行项目,要求输入聊天室名称(即订阅了相同的主题Topic)

  3.当2个客户端进入同一个聊天室的时候,彼此之间可以互相通信和收发消息

  4.当第3个客户端进入另外一个客户端的时候,不可以收到之前2个客户端发来的消息

  1.创建Windows Console项目,命名为ServiceBusScribe。图略。

  2.增加新的类ChatRoom.cs,增加如下代码:

using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ServiceBusScribe
{
class TextEventArgs :EventArgs
{
public ChatText ChatText{get; private set;}
public TextEventArgs (ChatText chatText)
{
ChatText = chatText;
}
}
class ChatRoom
{
public event EventHandler<TextEventArgs> TextReceived;
public string Name { get; private set; } TopicClient mTopicClient;
SubscriptionClient mSubscriptionClient;
//your servicebus namespace here
const string mConString = "Endpoint=sb://[YourServiceBusName].servicebus.chinacloudapi.cn/;SharedAccessKeyName=[YourServiceBusKey]"; public ChatRoom(string chatRoom, string userName)
{
Name = chatRoom;
NamespaceManager nm = NamespaceManager.CreateFromConnectionString(mConString);
TopicDescription desc = new TopicDescription(chatRoom);
desc.AutoDeleteOnIdle = TimeSpan.FromMinutes(); if (!nm.TopicExists(chatRoom))
//如果没有该Topic,则创建
nm.CreateTopic(chatRoom);
if (!nm.SubscriptionExists(chatRoom, userName))
//如果有该Topic,则订阅
nm.CreateSubscription(chatRoom, userName); mTopicClient = TopicClient.CreateFromConnectionString(mConString, chatRoom);
mSubscriptionClient = SubscriptionClient.CreateFromConnectionString(mConString, chatRoom, userName); mSubscriptionClient.OnMessage((m) =>
{
var text = m.GetBody<ChatText>(); if (TextReceived != null)
TextReceived(this, new TextEventArgs(text));
});
} public void Send(string user, int color, string text)
{
mTopicClient.Send(new BrokeredMessage(new ChatText(user, color, text)));
} public void Close()
{
mSubscriptionClient.Close();
mTopicClient.Close();
}
}
}

  注意:在上面的代码中,修改const string mConString参数,将连接字符串修改为我们自己的Service Bus连接字符串

  核心代码为上面的构造函数Public ChatRoom中

  

  3.增加新的类ChatText.cs,增加如下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization; namespace ServiceBusScribe
{
[DataContract]
class ChatText
{
[DataMember]
public string User { get; set; } [DataMember]
public string Text { get; set; } [DataMember]
public int Color { get; set; } public ChatText(string user, int color, string text)
{
User = user;
Text = text;
Color = color;
}
} }

  4.修改Program.cs,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Runtime.Serialization; namespace ServiceBusScribe
{
class Program
{
static int linePos = ; //当前显示行的位置
static int myColor = ; //为用户随机指定的颜色
static Array mColors = Enum.GetValues(typeof(ConsoleColor));
static void Main(string[] args)
{
Random rand = new Random();
myColor = rand.Next(, mColors.Length); //随机指定用户名颜色
Console.Clear();
Console.Write("请输入用户名:");
string userName = Console.ReadLine(); //输入新聊天室名,或者加入已有聊天室
Console.Write("请输入聊天室名:");
string chatRoom = Console.ReadLine(); //聊天室界面
Console.Clear();
Console.Write(userName);
Console.SetCursorPosition(Console.WindowWidth - chatRoom.Length, ); Console.Write(chatRoom);
Console.Write(new String('*', Console.WindowWidth));
Console.SetCursorPosition(, Console.WindowHeight - ); Console.Write(new String('*', Console.WindowWidth));
ChatRoom room = new ChatRoom(chatRoom, userName);
room.TextReceived += room_TextReceived;
while (true)
{
setCursorAtBottom();
var input = Console.ReadLine();
if (string.IsNullOrEmpty(input))
break;
room.Send(userName, myColor, input);
}
room.Close(); } static void setCursorAtBottom()
{
//这个方法把光标放在屏幕底部,供用户输入新信息
Console.SetCursorPosition(, Console.WindowHeight - );
Console.Write(new String(' ', Console.WindowWidth)); Console.SetCursorPosition(, Console.WindowHeight - );
Console.Write("] ");
} static void room_TextReceived(object sender, TextEventArgs e)
{
if (linePos >= Console.WindowHeight - )
{
for (int i = ; i < Console.WindowHeight - ; i++)
{
Console.SetCursorPosition(, i);
Console.Write(new string(' ', Console.WindowWidth));
}
linePos = ;
}
//显示接受到的新消息
Console.SetCursorPosition(, linePos);
Console.ForegroundColor = (ConsoleColor)mColors.GetValue(e.ChatText.Color);
Console.Write("[" + e.ChatText.User + "]:");
Console.ForegroundColor = ConsoleColor.White;
Console.Write(e.ChatText.Text);
linePos++;
setCursorAtBottom();
} }
}

  5.项目创建完毕后,记得增加对Microsoft.ServiceBus命名空间的引用。

  然后我们编译一下,并同时运行2个Windows Console实例。

  首先输入不同的用户名。

  然后再输入同样的聊天室名称,如下图的Game。

  

  我们进入同一个聊天室,显示如下:

  

  我们在左侧,以Jack身份输入Hello信息后。即可在两个聊天室窗口,同时看到聊天信息。如下图:

  

  同样的道路,我们在右侧的聊天窗口中,以Tom身份输入信息,也可以在两个聊天室窗口,同时看到聊天信息。

  

  6.最后,我们可以在Azure Management Portal,查看到我们创建的名为Game的Service Bus Topic,如下图:

  

  上图中,Game是笔者创建的聊天室名称。

  另外,我们在不关闭2个Windows Console窗口的情况下,可以看到Subscription Count为2。即2个客户端订阅了该Topic。

  

  参考文档:

  《Windows Azure实战》——(美)白海石,机械工业出版社

Windows Azure Service Bus (5) 主题(Topic) 使用VS2013开发Service Bus Topic的更多相关文章

  1. Windows Azure Service Bus (3) 队列(Queue) 使用VS2013开发Service Bus Queue

    <Windows Azure Platform 系列文章目录> 在之前的Azure Service Bus中,我们已经介绍了Service Bus 队列(Queue)的基本概念. 在本章中 ...

  2. Windows Azure Service Bus (6) 中继(Relay On) 使用VS2013开发Service Bus Relay On

    <Windows Azure Platform 系列文章目录> 注意:本文介绍的是国内由世纪互联运维的Windows Azure服务. 项目文件请在这里下载. 我们在使用Azure平台的时 ...

  3. Windows Azure Service Bus (4) Service Bus Queue和Storage Queue的区别

    <Windows Azure Platform 系列文章目录> 熟悉笔者文章的读者都了解,Azure提供两种不同方式的Queue消息队列: 1.Azure Storage Queue 具体 ...

  4. Windows Azure Cloud Service (11) PaaS之Web Role, Worker Role(上)

    <Windows Azure Platform 系列文章目录> 本文是对Windows Azure Platform (六) Windows Azure应用程序运行环境内容的补充. 我们知 ...

  5. Windows Azure HandBook (5) Azure混合云解决方案

    <Windows Azure Platform 系列文章目录> 在很多情况下,我们都会遇到本地私有云和公有云做互通互联的混合云场景.对于这种混合云的场景,微软的Windows Azure会 ...

  6. 无责任Windows Azure SDK .NET开发入门篇一[Windows Azure开发前准备工作]

    一.Windows Azure开发前准备工作 首先我们需要了解什么是 Azure SDK for .NET?微软官方告诉我们:Azure SDK for .NET 是一套应用程序,其中包括 Visua ...

  7. Windows Azure 安全最佳实践 - 第 3 部分:确定安全框架

    构建云应用程序时,安全始终是计划和执行Windows Azure的首要核心因素.第 1 部分提出安全是一项共同责任,Windows Azure为您的应用程序提供超出内部部署应用程序需求的强大安全功能. ...

  8. 无责任Windows Azure SDK .NET开发入门篇(一):开发前准备工作

    Windows Azure开发前准备工作 什么是 Azure SDK for .NET?微软官方告诉我们:Azure SDK for .NET 是一套应用程序,其中包括 Visual Studio 工 ...

  9. [Windows Azure] Developing Multi-Tenant Web Applications with Windows Azure AD

    Developing Multi-Tenant Web Applications with Windows Azure AD 2 out of 3 rated this helpful - Rate ...

随机推荐

  1. LDA和PLSA

    看了<LDA数学八卦>和July的博客,里面涉及到好多公式推导...感觉好复杂,于是记录一些重点简洁的东西,忽略大批量铺垫,直接回答LDA和PLSA是区别: 在pLSA模型中,我们按照如下 ...

  2. 0003--Weekly Meeting on 10th April and 17th April, 2015

    10th April, 2015 (1) Orthogonal Matching Pursuit, Least Angle Regression, Dictionary Coherence. -> ...

  3. VS2012 编译带有c/c++代码的python模块失败解决方案

    python2.7默认编译带有/c++代码的模块/包是使用VS2008环境变量,所以为了可用,我们要在编译前设置环境变量 SET VS90COMNTOOLS=%VS110COMNTOOLS% 但有时只 ...

  4. Java设计模式10:观察者模式

    观察者模式 观察者模式也叫作发布-订阅模式,也就是事件监听机制.观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,这个主题对象在状态上发生变化时,会通知所有观察者对象,使他 ...

  5. JedisPool异常Jedis链接处理

    问题现象(jedis-2.1.0.jar) 基于JedisPool管理Jedis对象,通过get方法获取值,出现key对应的value值错误,例如: K V a a b b Jedis.get(“a” ...

  6. C#反射基础知识和实战应用

    首先来说一下什么是反射? 反射提供了封装程序集.模块和类型的对象(Type类型) 可以使用反射动态的创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型,然后,可以调用类型的方法或访问其字段和 ...

  7. alwaysOn为什么不支持分布式事务

    Alwayson是微软从SQL2012开始引入的一种高可用和高性能架构,它既可以实现故障转移,同时又能实现查询分离,是当前SQL server的所有架构中最优秀的一种. 因此,一般我们都会推荐使用Al ...

  8. Intellij Idea 2016 配置Tomcat虚拟目录

    默认的idea是不需要配置虚拟目录了,它完全托管项目,但是有些时候,在开发过程中,是需要以虚拟目录的形式开发,即以:http://localhost:8080/虚拟目录名/index.html 这种形 ...

  9. 阿里巴巴B2B搜索学习

    1.搜索业务 主搜索:商品搜索.商家搜索.采购搜索.app搜索 行业搜索:淘货源.淘工厂.聚好货.主题市场.品牌馆等 2.优势 由于用户多,需求强烈,收益大,所以功能.场景.架构做到极致高效. 代码复 ...

  10. PHP面向对象之魔术方法复习

    魔术方法复习 2014-9-2 10:08:00 NotePad++ By jiancaigege 飞鸿影~========================= 1.__construct() 构造方法 ...