Thursday, 2 July 2015

SignalR Tutorial: Establishing a communication in server and client

Development In Server step by step: 

  1. Add SignalR reference from nuGet -> 
  2. Create a startup class to map signalR with App -> 
  3. Create a customHubClass inheriting Hub -> 
  4. Create a Hubmethod inside a class -> 
  5. Send data through "Clients" object

SignalR Tutorial: 

Implementation Step-by-step

i) Create a new web application in Visual studio
ii) Add nuget reference of SignalR
iii) Add a class Startup.cs as follows
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

iv) Add a class ChatHub.cs as follows
using System;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace Chat_Server_Application
public class ChatHub : Hub
public void Send(string name, string message)
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
[HubMethodName("ChatSendtoAllMethod")] // this method and this hubmethod name is used for client side implementation
public void SendToAll(string info)
Clients.All.broadcastMessage(name, message);

v) Add a html page for user interactive and this html file is meant for checking our signalR server code and not for client side implementation
<!DOCTYPE html>
<title>SignalR Simple Chat</title>
<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion"></ul>
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.6.4.min.js"></script>
<!--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>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {

// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.

chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>:&nbsp;&nbsp;' + encodedMsg + '</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.
// 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.
vi) Just set this html file as start up page and run this web application

Implementation In Client: 

Add SignalR client reference from nuGet ->
ask for SignalR url ->
Create Hubconnection object ->
Create HubProxies of hubconnection by mapping it to server ->
Hubconnection.Start() ->
Switch on the Hubproxies ->
Invoke the Hubmethods ->
Receive data (if required).

Some questions
1. What happens if url was wrong when creating a Hubconnection in client side implementation?
It will result in 404 Error in the http header as follows
StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
  Date: Tue, 30 Jun 2015 10:03:13 GMT
  Server: Microsoft-IIS/8.5
  X-Powered-By: ASP.NET
  Content-Length: 1245
  Content-Type: text/html

2. What happens if HubProxy name was wrong i.e. mentioned in the client doesnt not match with Server?
It will result in internal server if it was not handled properly
{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
  Transfer-Encoding: chunked
  Cache-Control: private
  Date: Tue, 30 Jun 2015 09:54:57 GMT
  Server: Microsoft-IIS/8.5
  X-AspNet-Version: 4.0.30319
  X-Powered-By: ASP.NET
  Content-Type: text/html; charset=utf-8

3. In server side implementation, What are the various ways to send message selectively or collectively using "Clients" objects ?
i) To send a msg to a particular user -> Clients.User(userId).send(message); or Clients.Client(ConnID).HubMethodName(message);

Please leave your doubts here in case of any clarifications required.

2 July 2015
The Other World

No comments:

Related Posts