Introduction
SignalR is a web-based, real-time bidirectional communication framework. It’s very useful in terms of user-friendliness. While developing a chat application or broadcasting the message like a notification popup, before SignalR came into the picture, we used to use the request/response technology where the server had to wait for the client’s request. On the other hand, in SignalR, we can directly push the message to the clients.
It has three important transport mediums, as mentioned below.
- Server-Sent Event.
- Forever Frame.
- Long Polling.
Implementation
Step 1. Open Visual Studio and create a new ASP.NET web application.
Step 2. Select MVC and authentication mode as “No Authentication”.
Step 3. Open the Package Manager Console and type the following command to install the NuGet package. Alternatively, click Add >> New Item >> SingalR and select SignalR Hub Class (v2), followed by a click on the OK button.
Install-Package Microsoft.AspNet.SignalR
Step 4. In the Myhub1.cs class, add the following method.
public void Send(string name, string message)
{
Clients.All.addNewMessageToPage(name, message);
}
Step 5. In Solution Explorer, right-click and add a new class with the name “Startup.cs” and then install “Microsoft.Owin'” NuGet package.
Step 6. Open the HomeController.cs class and add the chat method.
Step 7. Create a new View called “Chat” under the "Home" folder, delete the existing code from View, and add the below code.
@{
ViewBag.Title = "Chat";
}
<h2>Chat</h2>
<script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script>
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion"></ul>
</div>
@section scripts {
<!-- Script references. -->
<!-- The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!-- Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.1.0.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 () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.myHub1;
// Create a function that 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.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
}
Step 8. Create a chat menu in the _Layout.cshtml file as shown below.
<li>
@Html.ActionLink("Home", "Chat", "Chat")
</li>
Conclusion
Save all the files in Visual Studio and run the same. In the browser, the system will ask us to enter the name. Copy the http://localhost:62167/Home/Chat URL and put it into another browser tab.
That’s all. Now, we can enjoy the chat.
Code Sample
Startup.cs
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
}
ChatHub.cs
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the addNewMessageToPage method to update clients.
Clients.All.addNewMessageToPage(name, message);
}
}
Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}