Tuesday, January 15, 2013

Persistence API in SignalR

Adding onto this, one configures a route in RouteConfig as show here, and again, this is Mr. Sullivan's code.

routes.MapConnection<ChatConnection>("chat", "chat/{*operation}");

 
 

He (Brian Sullivan) made a view which looks like so:

<div id="chatArea"></div>
<div>
   <input type="text" id="chatText" />
   <button id="sendButton">Send</button>
</div>
@section scripts
{
   <script type="text/javascript" src="~/Scripts/jquery.signalR-1.0.0-rc1.js"></script>
   <script type="text/javascript">
      $(function () {
         var conn = $.connection("/chat");
         $("#sendButton").click(function () {
            conn.Send($("#chatText").val());
            $("#chatText").val("");
         });
         conn.received(function (data) {
            $("#chatArea").append("<div>" + data + "</div>");
         }
         conn.start().done(function() {
            if (conn.eventSource) {
               conn.eventSource.addEventListener('message', function(event) {
                  console.log("EventSource message: " + event.data);
               });
            }
         });
      });
   </script>
}

 
 

conn.Send($("#chatText").val()); above is going to send the contents of the chatText input field to a ChatConnection object as defined below. From there, am I not sure how the magic happens, but every browser listening via SignalR is going to get updated by SignalR! My notes have the ChatConnection object looking like so. I can't remember if the speaker added other lines to this object or not. Maybe all of the voodoo is in the view above and the C# object just empowers it, you know?

namespace SignalRChat
{
   using Microsoft.AspNet.SignalR;
   public class ChatConnection : PersistentConnection
   {
      protected override System.Threading.Tasks.Task OnReceivedAsync(IRequest
            request, string connectionId, string data)
      {
         return base.OnReceivedAsync(request, connectionId, data);
      }
   }
}

No comments:

Post a Comment