Create a live chat application using Signalr+asp.net

Source: Internet
Author: User
Tags live chat jquery library

I. Overview:

Use ASP. SignalR 2 To create a live chat application. add SignalR to the MVC 5 application and create a chat view to send and display the message.

In the demo, the Learning SIGNALR development tasks include:
Add that SignalR Library to the MVC 5 application.
Create a hub and a Hao startup class to push content to the client.
Use the SignalR jQuery library in the Web page to send messages and display updates from the hub.

The following screen shot shows the completed chat application running in the browser.

2. Achieve:

Create an ASP. NET MVC 5 application, install the SignalR library, add and create a chat application.

1> in Visual Studio, create a C # ASP. NET Framework 4.5, named Signalrchat, and click OK.

2> in the new ASP. NET Project dialog box, select MVC and click Change Authentication

Note: If the application chooses a different authentication provider, it will create the Startup.cs class, where no authentication is chosen for all of us to create a startup class ourselves.

3> Install SIGNALR
Open the Tools | Library Package Manager | Package Manager console, and then run the following command. This step adds a set of script files to the project and an assembly reference that enables the SignalR feature.

Input: Install-package Microsoft.AspNet.SignalR

The installation is complete, and a file like this appears under the Scripts folder:

4> Create a startup class:

Create a class under the root directory named startup:

 using   Owin;  using   Microsoft.owin; [Assembly:owinstartup ( typeof   ( Signalrchat.startup)]  namespace   signalrchat{ public  class   Startup { public  void   Configuration (Iappbuilder app) { //  connection or hub wire up and configuration should go to here   app.        MAPSIGNALR (); }    }}

5.> add an existing item to the project by adding the Hubs folder:
Right-click the Hubs folder, click Add | New project, select Visual C # | Web | So SignalR node in the installed pane, from the center pane, select the SignalR Hub Class (v2) and create the name ChatHub.cs.

To modify the code:

usingSystem;usingsystem.web;usingMicrosoft.AspNet.SignalR;namespacesignalrchat{ Public classChathub:hub { Public voidSend (stringNamestringmessage) {            //Call the Addnewmessagetopage method to update clients.Clients.All.addNewMessageToPage (name, message); }    }}

6>. Edit HomeController class discovery in Controllers/homecontroller.cs, add the following methods to the class. This method returns the view of the chat that you will create in a later step.

 Public ActionResult Chat () {    return  View ();}

7>. On the Chat () method, right-click > Add View Page

Modify the code to:

1 @{2Viewbag.title ="Chat";3 }45<divclass="Container">6<input type="text"Id="message"/>7<input type="Button"Id="SendMessage"Value="Send"/>8<input type="Hidden"Id="DisplayName"/>9<ul id="discussion"></ul>Ten</div> One @section Scripts { A<!--Script references. - -<!--the JQuery library isRequired and isReferenced bydefault inch_layout.cshtml. - -<!--Reference the SignalR library. - the<script src="~/scripts/jquery.signalr-2.0.3.min.js"></script> -<!--Reference the autogenerated SignalR hub script. - -<script src="~/signalr/hubs"></script> -<!--SignalR script to update the chat page and send messages.--> +<script> - $ (function () { +             //to create an object of the corresponding server-side hub class, note that the first letter of the Chathub (class name under the Hubs folder) is changed to lowercase A             varChat =$.connection.chathub; at             //defines the client-side JavaScript function for the server-side hub, which invokes all clients JavaScript function in a dynamic manner -Chat.client.addNewMessageToPage = function (name, message) {//Send in Fuction (name,message) =>chathub.cs here (string name, String message) -                 //when the server side calls SendMessage, the message data for server push is rendered in Wholemessage -$('#discussion'). Append ('<li><strong>'+HtmlEncode (name) -+'</strong>:'+ htmlEncode (message) +'</li>'); -             }; in             //Get the user name and store it to prepend to messages. -$('#displayname'). Val (Prompt ('Enter your name:',"')); to             //Set initial focus to message input box. +$('#message'). focus (); -             //Open the connection . the $.connection.hub.start (). Done (function () { *$('#sendmessage'). Click (function () { $                     //call the Hub object called the server side to pass #message data to the serverPanax NotoginsengChat.server.send ($ ('#displayname'). Val (), $ ('#message'). Val ()); -$('#message'). Val ("'). focus (); the                 }); +             }); A         }); the         //This optional function html-encodes messages for display in the page. + function HtmlEncode (value) { -             varEncodedvalue = $ ('<div/>'). Text (value). html (); $             returnEncodedvalue; $         } -</script> -}
View Code

F5 run the project can achieve the above effect, you can have the user in real-time synchronization chat.

Create a live chat application using Signalr+asp.net

Related Article

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.