Chat application using SignalR 2.1
Around two years ago I published a post about SignalR. Recently some readers requested an updated post using SignalR 2.1, here is the updated one.
For this post I created a very simple chat application that hosted in IIS, developed in .NET 4.5. Below is the project structure.
-
SignalrTracer.ChatServer: An empty ASP.NET Web Application which host the SignalR hub.
-
SignalrTracer.Publisher: A class library project that has SignalR hubs. I created this project just to isolate SignalR hubs from the ChatServer.
-
SignalrTracer.ChatClient: Another empty ASP.Net Web Application act as the client.
SignalrTracer.Publisher
As I mentioned above, this project contains the SignalR hubs. We can add SignalR framework using Nuget package manager.
Open Package Manager Console from Tools->Nuget Pacakger Manager and choose SignalrTracer.Published as the Default Project in the console window, then enter
PM> Install-Package Microsoft.AspNet.SignalR.Core
The command will add the SignalR and dependent frameworks. It’s time to create our chat hub.
ChatHub.cs
using Microsoft.AspNet.SignalR; namespace SignalrTracer.Publisher { public class ChatHub:Hub { public void Subscribe(string chatId) { Groups.Add(Context.ConnectionId, chatId); } public void Publish(string toChatId, string message) { Clients.Group(toChatId).flush(message); } } }
SignalR 2.1 relies on OWIN to host it. For that we need to create a Startup class as shown below.
using Microsoft.Owin; using Owin; using Microsoft.AspNet.SignalR; [assembly: OwinStartup(typeof(SignalrTracer.Publisher.Startup))] namespace SignalrTracer.Publisher { public class Startup { public void Configuration(IAppBuilder app) { // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888 var hubConfig = new HubConfiguration(); hubConfig.EnableDetailedErrors = true; hubConfig.EnableJSONP = true; app.MapSignalR("/chatserver", hubConfig); app.Run(async context => { await context.Response.WriteAsync("Chat server started"); }); } } }
That’s it we created our SignalR hub. Let’s host it in our ChatServer.
SignalrTracer.ChatServer
This project is a OWIN host, to do that we need to refer another Nuget package called Microsoft.Owin.Host.SystemWeb.
Open the Nuget Package Manager Console and set Default project as SignalrTracer.ChatServer, then enter
PM> Install-Package Microsoft.Owin.Host.SystemWeb
Once all the package installed, just refer SignalrTracer.Publisher project and run the project. If every thing is fine then you can see an Internet Explorer with a string Chat server started. This means SignalR hub is up and running and any clients can connect now.
SignalrTracer.ChatClient
I used Javascript to connect to SignalR server. Open Nuget Package Manager Console and enter
PM> Install-Package Microsoft.AspNet.SignalR.JS
It will install JQuery and JQuery extension of SignalR client. I created an index.html and added the code below.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="Scripts/jquery-1.6.4.min.js"></script> <script src="Scripts/jquery.signalR-2.1.2.min.js"></script> <script type="text/javascript"> $(function () { var connection = $.hubConnection('http://localhost:35144/chatserver'); var proxy = connection.createHubProxy('ChatHub'); connection.start() .done(function () { $('#messages').append('<li>Connected to chat</li>'); }) .fail(function () { alert("Could not Connect!"); }); proxy.on('flush', function (msg) { $('#messages').append('<li>' + msg + '</li>'); }); $("#send").click(function () { proxy.invoke('Publish', $("#sendTochatId").val(), $("#message").val()); }); $("#connect").click(function () { proxy.invoke('subscribe', $("#chatId").val()); $('#messages').append('<li>subscribed to chat</li>'); }); }); </script> <title></title> </head> <body> <label>Chat id</label> <input type="text" id="chatId" /><input type="button" id="connect" value="Connect" /><br /> <label>Send To</label> <input type="text" id="sendTochatId" /><br /> <label>Message</label> <input type="text" id="message" /> <input type="button" id="send" value="Send"/> <div> <ul id="messages"></ul> </div> </body> </html>
You might need to change the url of hubConnection marked in bold.
Once the connection established messages section will get appended with ‘Connected to chat’ message.
Enter a unique Id in Chat Id text and click Connect, open multiple window and connect with different chat id’s.
As you can see it’s a very basic and simple chat system based on SignalR.
Happy coding…
[…] Updated post about how to create a chat application using SignalR 2.1 […]
SignalR – Real time pushing of data to connected clients | Sony Arouje Blog
September 18, 2014 at 12:56 am
Every time I try running the HTML page, I receive a “Could Not Connect” message. What am I doing wrong?
Garrett
October 7, 2014 at 6:56 pm
I am trying to build a site with group and private chat on it. To be more clear, instead of all the users online on this site, we want only the respective city’s users to be on the group and if clicked on a particular name, we could able to chat privately with him/her.
So, in London, we can only see people online from London and everybody can see our chat message until we choose anyone particularly. Similarly, for other cities as well.
So, I need to pick DB values of the username (their cities) to provide for the group chat membership and also limit the visibility of the group to other cities and their messages of that group.
Kindly suggest me.
NOTE: I need to do this on Web form only, since 80% of the site has already been done on Asp.Net Web form.
Thanks in advance and have a nice day ahead.
Praveen
November 25, 2014 at 6:18 pm
Hi,
Sorry for the late reply. There is a group publishing option in signal R. Try to use that option. I am a bit occupied now, so unable to give you the right details, I am sorry for that.
Regards,
Sony Arouje
Sony Arouje
March 3, 2015 at 11:51 am
Hi Sonya! thank you for the tutorials. Its been a great help for starters. Just downloaded the file and load it up in my VS2013. However, after running the SignalRTracer.ChatClient it does not run on Chrome and displays a message “Could not connect” but when viewing the site in IE browser, it runs fine without problem. Can you please help? Thank you
DC 7
March 3, 2015 at 8:30 am
Hi,
I was not clear what went wrong at your end, probably a network trace using chrome (press F12 key) might reveal the issue.
Regards,
Sony Arouje
Sony Arouje
March 3, 2015 at 11:48 am
Please Provide a Code Sample to create a group chat in SignalR…
Thanks
Apurba
Apurba
May 28, 2015 at 12:38 pm
Hi Apurba,
You can do a search in google and you can find a lot of chat solutions using SignalR.
Regards,
Sony Arouje
Sony Arouje
September 3, 2015 at 10:35 pm