Monday, February 18, 2013

SignalR with PersistentConnection

In my previous post I explained about how to use Hub connections in SignalR. In this post I'll show how to use PersistentConnection with SignalR.

Create an ASP.net empty web application. Install Microsoft.AspNet.SignalR through nuget.
Create MessageConnection class like below. You should override OnReceived method. When message received to the MessageConnection, that message will broadcast to all clients.
Now we have to map this class to route table. So add Global.asax file and in Application_Start method map the MessageConnection class like below. We have to pass two parameters : Name for the connection and routing URL.
Add OnlineConnection.html file. When we enter a value in txtMessage text box, and press btnSend, that message will go to server and result will show in the message div.
We need to add two java script libraries. Jquery and SignalR. When web page is loaded, we need to define the connection. This is a PersistentConnection and we have mapped URL as "/message". Because we mapped the URL like that in Global.asax. When the the SignalR MessageConnection  started, we have to bind click function to the btnSend. In click function we send data to MessageConnection. This will broadcast  received messages. So in java script, when message received, we append that text to message div.
You can find the source of this demo in GitHub.

No comments:

Post a Comment