Development environment: vs2013+.net4.5+mvc5+jquery.signalr-2.2.0
1. New Project
Choose MVC
2. Find SIGNALR online with NuGet
Installation of the first
3. Add the Hub folder to the project directory and create a new Chathub class inside it, with the following code:
Public class ChatHub:Microsoft.AspNet.SignalR.Hub { publicvoid Hello () { Clients.All.hello (); } Public void Send (stringstring message) { // Call the Addnewmessagetopage method to update clients. Clients.All.addNewMessageToPage (name, message); } }
4. Add the Startup class in the project directory with the following code:
usingMicrosoft.owin;usingOwin;usingsignalrchat_mysample;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web; [Assembly:owinstartup (typeof(Startup))]namespacesignalrchat_mysample{ Public classStartup { Public voidConfiguration (Iappbuilder app) {//Any connection or hub wire up and configuration should goapp. MAPSIGNALR (); } }}
5. Create a new chat method and corresponding view in the home controller
Public actionresult Chat () { return View (); }
@{viewbag.title = "chat room";}<H2>Chat room</H2><Divclass= "Container"> <inputtype= "text"ID= "message" /> <inputtype= "button"ID= "SendMessage"value= "Send" /> <inputtype= "hidden"ID= "DisplayName" /> <ulID= "discussion"></ul></Div>@section Scripts {<!--Script references. - <!--The JQuery Library is required and was referenced by default in _layout.cshtml. - <!--Reference the SignalR library. - <Scriptsrc= "~/scripts/jquery.signalr-2.2.0.min.js"></Script> <!--Reference the autogenerated SignalR hub script. - <Scriptsrc= "~/signalr/hubs"></Script> <!--SignalR script to update the chat page and send messages. - <Script> $(function () { //Reference The auto-generated proxy for the hub. varChat=$.connection.chathub; //Create a function, the hub can call back to display messages.Chat.client.addNewMessageToPage= function(name, message) {//ADD the message to the page. $('#discussion'). Append ('<li><strong>' +HtmlEncode (name)+ '</strong>:' +htmlEncode (message)+ '</li>'); }; //Get the user name and store it to prepend to messages. $('#displayname'). Val (Prompt ('Enter your name:', "')); //Set initial focus to message input box. $('#message'). focus (); //Start the connection.$.connection.hub.start (). Done (function () { $('#sendmessage'). Click (function () { //Call the Send method on the hub.Chat.server.send ($ ('#displayname'). Val (), $ ('#message'). Val ()); //Clear text box and reset focus for next comment. $('#message'). Val ("'). focus (); }); }); }); //This optional function html-encodes messages for display in the page. functionHtmlEncode (value) {varEncodedvalue= $('<div/>'). Text (value). html (); returnEncodedvalue; } </Script>}
Complete
SOURCE download
SIGNALR Building Chat Room Tutorial