In last post I explained what SignalR, why do us need it is and what are the prerequisites.
In this
tutorial we’ll use ASP.NET SignalR to create a real-time chat application.
First of
all we’ll add SignalR library to an MVC 4 application and then create hub class
(to push content to client) and after that we’ll use SignalR jQuery library to
send messages and display updates from the hub.
·
Open
Visual Studio -> Select ASP.NET MVC4 Web Application template (under Web
Templates) and enter the name of application as “MVCSignalRApp” and then click
OK.
·
On
the next screen select “Internet Application” template and then click OK.
·
Your
basic MVC application is ready to use, now we need to add SignalR libraries to
this application. To add SignalR libraries open Package Manager Console (TOOLS
- >Library Package Manager -> Package Manager Console) and then run
following command.
install-package Microsoft.AspNet.SignalR
|
·
It’ll
add all the required SignalR libraries to our application. For instance you can
check SignalR JavaScript files under Script folder. Application references are
also updated in our application.
·
In
Solution Explorer, right-click on the project, select Add -> New Folder, and
name the new folder as “SignalRHub”.
·
Under
this folder Add a new class and give it a name as “ChatHub.cs” and replace the
code of this class with the following code:
using System;
using System.Web;
using
Microsoft.AspNet.SignalR;
namespace
MvcSignalRApp.SignalRHub
{
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the 'addNewMessageToPage' method to update
clients.
Clients.All.addNewMessageToPage(name, message);
}
}
}
|
Understand the code of ChatHub class:
§ In the above code the ChatHub class
derives from the Hub (under Microsoft.AspNet.SignalR namespace) class. Deriving
from the Hub class is a useful way to build a SignalR application.
§ We can create public methods in hub
class and then we can access those methods by calling them from jQuery scripts
in a web page. In this case we have defined one public method “Send”; clients
call the ChatHub.Send method to send a new message. In the “send” method jQuery
“addNewMessageToPage“(through “Clients.All”) method is called through which the
hub sends the message to all clients.
§ In the “addNewMessageToPage” method
display name of user and message entered by user is sent to browser to display
for all other clients.
·
Open
the Global.asax file and add a call to the method RouteTable.Routes.MapHubs()
in the “Application_Start” method to register the default route for SignalR hubs.
This code must be called before you register any other routes through
Global.asax.
protected void
Application_Start()
{
// Register the default hubs route: ~/signalr/hubs
RouteTable.Routes.MapHubs();
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
|
·
Open
the Controllers -> HomeController.cs and add the “ChatApp” method to the
class. This method returns the ChatApp view that we’ll create in a later step.
public ActionResult
ChatApp()
{
return View();
}
|
·
Right-click
on the ChatApp method you just created, and click Add View to create a new view
file.
·
On
the next screen give your view a name and mark the “Use a layout or master page”
checkbox to check and click on Add.
·
Open
the view file ChatApp.cshtml. And After the <h2> tag, paste the mentioned
below <div> section and @section scripts code block into the page. This
script enables the page to send chat messages and display messages from the
server.
<div class="container">
<h3>UserName:
<label id="userName" style="display: inline;"></label>
</h3>
<input type="text" id="messageBox" />
<input type="button" id="sendMessage" value="Send" />
<ul id="messageList"
style="list-style: none; padding-left: 0px;">
</ul>
</div>
@section scripts {
<!--Script references. -->
<!--The jQuery library are referenced by default in
_Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-1.1.3.js"></script>
<!--Reference the autogenerated SignalR hub script.
-->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the ChatApp page and
send messages.-->
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat =
$.connection.chatHub;
//
Create a function that the hub can call back
// to
display messages.
chat.client.addNewMessageToPage = function (name, message) {
// Add the user message to the page.
$('#messageList').append('<li><strong>'
+ encodeHtml(name) + '</strong>:
'
+ encodeHtml(message) + '</li>');
};
// Get the user name and store it to prepend to
messages.
$('#userName').text(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#messageBox').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendMessage').click(function () {
//
Call the Send method on the hub.
chat.server.send($('#userName').text()
, $('#messageBox').val());
// Clear text box and reset focus for
next comment.
$('#messageBox').val('').focus();
});
});
});
// This optional function html-encodes messages
// for
display in the page.
function encodeHtml(value)
{
var ecValue = $('<div />').text(value).html();
return ecValue;
}
</script>
}
|
“Comments have
been added to code for better understanding, however please make sure that
the script references in your code match the versions of the script libraries
installed in your project as VS Package manager might install most recent versions
of the scripts than the versions shown in this post.”
|
·
Save
all of your work and then press F5 to see our SignalR chat application in
action.
·
By
default you’ll see home screen of application, I have added Chat link (on top
right corner after Contact link) to navigate user to chat page. Click on this
link to open chat.
·
Once
you navigate to the chat page, it’ll ask for your name that will display
against your chat messages, enter the name and click OK.
·
Open
this page in different browser and same way enter the name, so now we have two users
ready for real time chat.
·
Enter
the message from any of the browser window and you can see that message in both
windows against the display name of user.
This
sample chat application does not maintain discussion context on the server
and user cannot see the old messages.
|
Summary:
In this
tutorial we have learned:
·
How
to add SignalR libraries to an ASP.NET MVC 4 application
·
Create
and use the hub class.
·
Register
the default route for SignalR hubs.
·
Send
and receive messages from the hub
You can download the source code of this sample for reference.
That’s
it for now, hope you have enjoyed learning SignalR; it’s an awesome framework
to create real-time, multi-user interactive web applications.
where to find autogenerated hub script?
ReplyDeleteThank you Kumar, it's very usefull for me
ReplyDeleteVery nice.
ReplyDeleteHello sir i'm newbie, while creating the above application the following error is occurred,
ReplyDeleteError 1 'System.Web.Routing.SignalRRouteExtensions.MapHubs(System.Web.Routing.RouteCollection)' is obsolete: 'Use IAppBuilder.MapSignalR in an Owin Startup class. See http://go.microsoft.com/fwlink/?LinkId=320578 for more details.' c:\users\t.sandeep\documents\visual studio 2013\Projects\MvcSignalRApp\MvcSignalRApp\Global.asax.cs 19 13 MvcSignalRApp
Plz help me out ASAP
thanks in advance
Nice article. Do you have any example which save data in sql server database?
ReplyDelete