The Windows Azure Service Bus (4) topic (TOPIC) uses VS2013 to develop Service bus Topic

Source: Internet
Author: User

Windows Azure Platform Family of articles Catalog

In the author's previous article in Windows Azure Service Bus (1) Foundation

Describes the Service Bus Support topic (TOPIC). Such as:

  

When 2 clients subscribe to the same topic (TOPIC) at the same time. When a message is sent to this topic, 2 clients receive the message at the same time.

 The author simulates an online chat room scene:

1. Create a Windows console command-line project and write the appropriate code

2. Run the project and ask for the chat room name (i.e. subscribe to the same topic topic)

3. When 2 clients enter the same chat room, they can communicate with each other and send and receive messages.

4. When a 3rd client enters another client, it is not possible to receive messages from the previous 2 clients

  1. Create a Windows Console project named Servicebusscribe. Entries

2. Add the new class ChatRoom.cs and add the following code:

usingMicrosoft.servicebus;usingMicrosoft.ServiceBus.Messaging;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceservicebusscribe{classTexteventargs:eventargs { PublicChattext chattext{Get;Private Set;}  PublicTexteventargs (Chattext chattext) {Chattext=Chattext; }    }    classChatroom { Public EventEventhandler<texteventargs>textreceived;  Public stringName {Get;Private Set; }        Topicclient mtopicclient;        Subscriptionclient msubscriptionclient; //your Servicebus namespace here        Const stringMconstring ="endpoint=sb://[yourservicebusname].servicebus.chinacloudapi.cn/; Sharedaccesskeyname=[yourservicebuskey]";  PublicChatroom (stringChatroom,stringuserName) {Name=chatroom; NamespaceManager nm=namespacemanager.createfromconnectionstring (mconstring); Topicdescription desc=Newtopicdescription (chatroom); Desc. Autodeleteonidle= Timespan.fromminutes (Ten); if(!nm. Topicexists (chatroom))//If you do not have the topic, createnm.            Createtopic (chatroom); if(!nm. Subscriptionexists (chatroom, userName))//if the topic is available, the subscriptionnm.            Createsubscription (chatroom, userName); Mtopicclient=topicclient.createfromconnectionstring (mconstring, chatroom); Msubscriptionclient=subscriptionclient.createfromconnectionstring (mconstring, chatroom, userName); Msubscriptionclient.onmessage ((m)=            {                varText = m.getbody<chattext>(); if(Textreceived! =NULL) textreceived ( This,NewTexteventargs (text));        }); }         Public voidSend (stringUserintColorstringtext) {Mtopicclient.send (NewBrokeredmessage (Newchattext (user, color, text)); }         Public voidClose () {msubscriptionclient.close ();        Mtopicclient.close (); }    }}

Note: In the above code, modify the Const string Mconstring parameter to modify the connection string to our own service bus connection string

  The core code is the above constructor in public chatroom

  

3. Add the new class ChatText.cs and add the following code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Runtime.Serialization;namespaceservicebusscribe{[DataContract]classChattext {[DataMember] Public stringUser {Get;Set; } [DataMember] Public stringText {Get;Set; } [DataMember] Public intColor {Get;Set; }  PublicChattext (stringUserintColorstringtext) {User=user; Text=text; Color=color; }    }}

4. Modify the Program.cs code as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Runtime.Serialization;namespaceservicebusscribe{classProgram {Static intLinepos =2;//the position of the currently displayed row        Static intMyColor =1;//randomly assigned colors for the user        StaticArray mcolors = Enum.getvalues (typeof(Consolecolor)); Static voidMain (string[] args) {Random Rand=NewRandom (); MyColor= Rand. Next (0, mcolors.length);//randomly specify user name colorconsole.clear (); Console.Write ("Please enter user name:"); stringUserName =Console.ReadLine (); //Enter a new chat room name, or join an existing chat roomConsole.Write ("Please enter a chat room name:"); stringChatroom =Console.ReadLine (); //Chat Room Interfaceconsole.clear ();            Console.Write (UserName); Console.setcursorposition (Console.windowwidth-Chatroom.length,0);            Console.Write (chatroom); Console.Write (NewString ('*', Console.windowwidth)); Console.setcursorposition (0, Console.windowheight-4); Console.Write (NewString ('*', Console.windowwidth)); Chatroom=Newchatroom (chatroom, userName); Room. Textreceived+=room_textreceived;  while(true) {setcursoratbottom (); varinput =Console.ReadLine (); if(string. IsNullOrEmpty (input)) Break; Room.            Send (userName, MyColor, input); }.        Close (); }        Static voidSetcursoratbottom () {//This method puts the cursor at the bottom of the screen for the user to enter new informationConsole.setcursorposition (0, Console.windowheight-3); Console.Write (NewString (' ', Console.windowwidth)); Console.setcursorposition (0, Console.windowheight-3); Console.Write ("] "); }        Static voidRoom_textreceived (Objectsender, Texteventargs e) {            if(Linepos >= Console.windowheight-4)            {                 for(inti =2; I < console.windowheight-4; i++) {console.setcursorposition (0, i); Console.Write (New string(' ', Console.windowwidth)); } Linepos=2; }            //Show new messages that are receivedConsole.setcursorposition (0, 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. Once the project is created, remember to add a reference to the Microsoft.servicebus namespace.

Then we compile and run 2 instances of the Windows console at the same time.

Enter a different user name first.

Then enter the same chat room name, like the game.

  

We enter the same chat room, which shows as follows:

  

We are on the left, after entering hello information as Jack. You can see the chat message in the two chat rooms window. Such as:

  

The same way, we are in the Chat window on the right, enter the information as Tom, or in the two Chat room window, also see chat information.

  

6. Finally, we can look at the azure Management Portal to see the service Bus Topic we created named game, such as:

  

, the game is the name of the chat room created by the author.

In addition, we can see that subscription count is 2 without shutting down the 2 Windows console window. That is, 2 clients subscribed to the topic.

  

Reference Documentation:

"Windows Azure Combat"--(MEI) Baihaishi, mechanical industry Press

The Windows Azure Service Bus (4) topic (TOPIC) uses VS2013 to develop Service bus Topic

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.