How to use Signalr with Redis to create a simple chat application
Before I get into the technical parts of this blog, I would like to give a brief summary about why I chose this topic. In my work, we have a task tracking board similar to Trello where cards are frequently moved around to different groups. The problem was that other users were not able to get the updates from other users. So, we used Signalr to do update the board whenever changes were made. All was well and good, until we created a public version of the site. The board was still updating but only within the context of the site. For example, the changes made to the public site wasn’t updating the intranet site and vice versa. This is when we decided to integrate Signalr with Redis. Redis backplane acts like a middleman between the two sites and notifies all subscribed sites with any changes.
- Create a new basic MVC project in Visual Studio 2012.
- Use NuGet manager to install Microsoft.ASP.Net Signalr. This will also install all the necessary library dependencies.
- Create a Hubs folder, and add a new class “ChatHub.cs”.
- In this same root directory, add a new class “Startup.cs”. Insert the code below:
- Create a Home controller and a view. Replace all contents of Index.html with the code below:
- That’s it! You can run the chat application using localhost. Next, I will show you how to integrate Signalr with Redis.
- Let’s first setup a folder that is accessible by IIS. Create a new folder “c:\dev\chatapp”. Using VS publish the site to this folder
- Create two sites “chata.web” and “chatb.web” and bind it to the chatapp folder. Don’t forget to update your application pool to .Net4 and add an entry into your “windows\system32\drivers\etc\hosts” file. For simplicity, I will refer to “chata.web” and “chatb.web” as CA and CB respectively,
- Open CA using Chrome. Open CA using Firefox. Because we are using the same site, we can still chat. But, when we open CB we can’t chat to CA. Signalr only works if its running on the same site.
- This is where Redis comes in. Download and install the package below. This will create a windows service serving as a backplane for the two sites. Once installed, go to the cmd prompt and type “services.msc”, look for “Redis Server”. By default, this service is not started, so right click and start the service. Right click the service, click properties, go to “General” tab and set startup type to “Automatic”. Also, on the “Log On” tab set Log on as to Local System Account.
Download Redis for Windows
- Use NuGet manager to install “Microsoft.AspNet.SignalR.Redis”.
- Replace “startup.cs” with the code below:
- Publish your site. Now test CA and CB. And voila! We can now chat between CA and CB.
The complete source code can be downloaded from my Github repository located here.