SignalR: example chat application

I remember myself a tweet from Scott Hanselman a couple of months ago, where he asked us to check out a small application he wrote. As one of  the first testers of his new "thing", I was interested but there were no documentation or libs available yet.

!(http://www.hanselman.com/blog/content/binary/WindowsLiveWriter/Asynchronousscalablewebapplicationswithp_122E/SignalR%20Chat%20-%20Google%20Chrome%20%2869%29_thumb.png)

A couple of days a go, I read a blogpost from Maarten Balliauw about SignalR. . Because I allready heard about SignalR a couple of months ago, I had to develop a very small application to test how it really works.

1. Install SignalR package

You also have to update the jquery package to 1.6.2 or higher!(/images/jeroenb/signalr-starter-application/6f76bc2f-o_nuget.png)

2. Create a chat class

We only want 1 chat instance so use the Singleton pattern, lazy creation because that's thread safe.


 public class Chat
 {
 private readonly static Lazy _instance = new Lazy( => new Chat);
 public static Chat Instance
 {
 get
 {
 return _instance.Value;
 }
 }
 }

3. Create a (chat)hub

Create a class ChatHub which will inherit from Hub

Have a look at the HubName attribute. That's the name you will use in javascript to define the connection.


 [HubName("chatHub")]
 public class ChatHub: Hub
 {
 private readonly int TimeoutInSeconds = 30;
 private readonly Chat _chat;

 public ChatHub: this(Chat.Instance) { }

 public ChatHub(Chat chat)
 {
 _chat = chat;
 }
 }

4. Javascript connection

Create a connection between the client and the server. When the connection has been started, we want to call the join method on the server.

var chatHubClient = $.connection.chatHub;
// Start the connection
$.connection.hub.start(function  {
chatHubClient.join('@Model.Name');
});

5. Model

Define a callback method on the server in the Chathub class

 public void Join(string myName)
 {
 if (Chat.Clients.Where(x => x.Name.Equals(myName)).Count.Equals(0))
 {
 Chat.Clients.Add(new Client { Name = myName, LastResponse=DateTime.Now });
 SendMessageServer(string.Format("{0} entered the chat", myName));
 GetClients;
 Caller.Naam = myName;
 }
 else
 throw new Exception("This login is allready in use");
 }

Download the Chat Application Example

Get more information on GitHub Listen to a podcast about SignalR on DotNetRocks

This article is part of the GWB Archives. Original Author: Jeroen Bourdeaud'hui

New on Geeks with Blogs