Building Web Apps with SignalR, part 1

Source: Internet
Author: User

Building Web Apps with SignalR, part 1

In the first installment of App-building with SignalR, learn how to build a real-time chat application.

    • by Eric Vogel
    • 01/22/2013
    • GET CODE DOWNLOAD

More on this topic:

    • Building a Chat Web App with Signal R, part 2

is sick of that dreaded page refresh? Want to turn your WEB application up to 11? If you've answered yes to either question, SignalR are for you. With SignalR, you can provide the content to your users in the real-time, all from ASP. Most importantly, it's compatible with browsers ranging all the the the-the-the-same-to-ie6! SignalR uses WebSockets on supported browsers and would fall back to server-side events, Forever Frame, or AJAX long Pollin G if needed. This means your can use a single library and not having to worry about that minutia.

There is approaches you can use with SignalR to achieve real-time communications:a persistent connection or a hub. The persistent connection API allows you-keep open a persistent connection between the client and server to send and re Ceive data. The Hub API is a abstraction above the persistent connection API, and is a suitable for remote procedure calls (RPC).

This article'll focus on the persistent connection API. I believe the best-learn a new technology is-to-build something useful with it, so we'll create a chat client using SignalR. To get started, create a new C # ASP 4 project from Visual Studio and then select the Web API option for your Pro Ject type. Next, install the Microsft SignalR pre-release NuGet package through the NuGet package Manager (Figure1).


[Click on the image for larger view.]
Figure 1. Installing the SignalR pre-release NuGet package.

In order to support IE 6 and 7, install the Json-js-json2 NuGet package as well, as shown in Figure2.


[Click on the image for larger view.]
Figure 2. JSON2 NuGet package installation.

Without further ado, let's get started on the This app. First create a new folder in the project named Chat. Then create a new class named Chatconnection within the Chat directory that inherits from Persistentconnection. You'll need to add a using statement for the Microsoft.AspNet.SignalR namespace.

Now open up the Routeconfig class under the App_start folder in the project. ADD a using statement for the Microsoft.Asp.Net.Signal namespace to the Routeconfig class:

Using Microsoft.AspNet.SignalR;

Next, register the Chatconnection class to the ' chat ' route in the RegisterRoutes method in the Routeconfig class:

Routetable.routes.mapconnection<chatconnection> ("chat", "chat/{*operation}");

Your completed Routeconfig class should resemble Listing 1.

Now-to-create the Chatdata data structure that would be is used to interchange data between the client and the server. Create a new class named Chatdata with Message and Name string data type properties:

namespace vsmsignalrsample.chat{public    class Chatdata    {public        string Name {get; set;}        public string Message {get; set;}        Public Chatdata ()        {        } public        Chatdata (string name, String message)        {            name = name;            message = Message;}}}    

Now it's time to finish implementing the Chatconnection class, which'll receive and broadcast chat messages. ADD using statements for the System.Threading.Tasks and Newtonsoft.json namespaces. Next, add a private dictionary<string, string> to store the clients that connect to the chat:

Private dictionary<string, string> _clients = new dictionary<string, string> ();

The Persistentconnection base class includes functionality for dealing asynchronously with a few critical server-side even TS such as a new connection, disconnection, reconnection and data retrieval. Let ' s implement the Onconnectedasync event handler first. When a new user first joins the same, they ' re added to the _clients Dictionary object, which'll be used to map the user ' s chosen chat name with their connectionid. Then a broadcast message was sent to all users, letting them know a new user have joined the chat:

protected override Task Onconnectedasync (irequest request, String ConnectionID) {    _clients. Add (ConnectionID, String. Empty);    Chatdata chatdata = new Chatdata ("Server", "A new user has joined the");    Return Connection.broadcast (Chatdata);}

Now it's time to tackle data retrieval from a connected client through the Onreceivedasync event handler. First, the JSON data object from the client was desterilized into a Chatdata object through Json.NET. Then the user's name is stored in the _clients dictionary. Finally, the user ' s chatdata is broadcast to all users:

protected override Task Onreceivedasync (irequest request, String ConnectionID, String data) {    Chatdata chatdata = Json convert.deserializeobject<chatdata> (data);    _clients[connectionid] = chatdata.name;    Return Connection.broadcast (Chatdata);}

The last event to handle is client disconnection, via the Ondisconnectedasync method. When a user disconnects, he or she's removed from the _clients dictionary. Then a message was broadcast to all users, letting them know a user have left the the class:

protected override Task Ondisconnectasync (irequest request, String ConnectionID) {    string name = _clients[ ConnectionID];    Chatdata chatdata = new Chatdata ("Server", String. Format ("{0} has left the" the ", name));    _clients. Remove (ConnectionID);    Return Connection.broadcast (Chatdata);}

Now it's time to create the Client-side JavaScript that would communicate with the persistent chat connection to display in Coming chat messages and chat hostel events to the user. Create a new JavaScript file named Chatr.js within the Scripts folder. The first step is to retrieve the server Chat connection object through the SignalR JavaScript plug-in:

var myconnection = $.connection ("/chat");

Next, the received event is set up to display a received chat message as a new list item element in the messages unordered List DOM element:

Myconnection.received (function (data) {        $ ("#messages"). Append ("<li>" + data. Name + ': ' + data. Message + "</li>");    });

After this, the error handler for the connection are set to display a console warning. This was mainly to ease debugging of the chat connection:

Myconnection.error (function (Error) {        Console.warn (error);    });

Lastly, a connection is initiated to the chat server and a continuation are set up to handle the message send Button-click Event. Within the Button-click event handler, the user ' s name and message is retrieved from the name and message text boxes, res Pectively. Then the user ' s name and message is sent to the chat server as a JSON object, as shown in Listing 2.

Now it's time to set up the UI for the Web application. Add a new MVC View class to the Home directory, named Chatr, which binds to the Chat.chatdata model. In the bottom of the view Add a script reference to the ~/sciprts/chatr.js script created earlier:

@{    viewbag.title = "Chat";} 

Now, add a controller action method named Chatr to the HomeController that returns a new view bound to an empty chat.chatd ATA object:

Public ActionResult Chatr () {     var vm = new Chat.chatdata ();     return View (VM); }

That's it:sit back, relax and invite a few friends-try out your The new chat app, shown in Figure 3.


[Click on the image for larger view.]
Figure 3. the completed real-time chat application.

As can, see SignalR are quite easy to work with and the persistentconnection API is very flexible. With SignalR, you can tackle a plethora of the real-time Web app use cases from the business to gaming. Stay tuned for the next installment, which covers how to use the SignalR Hub API to create a dynamic form.

More on this topic:

    • Building a Chat Web App with Signal R, part 2

About the Author

Eric Vogel is a Sr. Software Developer @ Kunz, Leigh, & Associates in Okemos, MI. He is the president of the Greater Lansing User Group for. NET. Eric enjoys learning about software architecture and craftsmanship, and are always looking for ways to create more robust a nd testable applications. Contact him at [email protected]

PRINTABLE FORMAT

Building Web Apps with SignalR, part 1

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.