Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Real time updates using Web Service

I'm trying to find examples on how to get real time updates using a web service in ASP.NET MVC (Version doesn't matter) and posting it back to a specific user's browser window.

A perfect example would be a type of chat system like that of facebooks' where responses are send to the appropriate browser(client) whenever a message has been posted instead of creating a javascript timer on the page that checks for new messages every 5 seconds. I've heard tons of times about types of sync programs out there, but i'm looking for this in code, not using a third party software.

What i'm looking to do specifically:

I'm trying to create a web browser chat client that is SQL and Web Service based in ASP.NET MVC. When you have 2-4 different usernames logged into the system they chat and send messages to each other that is saved in an SQL database, then when there has been a new entry (or someone sent a new message) the Web Service see's this change and then shows the receiving user the new updated message. E.G Full Chat Synced Chat using a Web Service.

The thing that really stomps me in general is I have no idea how to detect if something new is added to an SQL table, and also I have no idea how to send information from SQL to a specific user's web browser. So if there are people userA, userB, userC all on the website, i don't know how to only show a message to userC if they are all under the username "guest". I would love to know hot to do this feature not only for what i'm trying to create now, but for future projects as well.

Can anyone point me into the right direction please? I know SQL pretty well, and web services i'm intermediate with.

like image 886
eqiz Avatar asked Oct 28 '25 00:10

eqiz


1 Answers

You can use SignalR for this task.

Via Scott Hanselman:

  1. Create Asp.net mvc empty application

  2. install nuget package of SignalR

  3. Add new Controller (as example HomeController):

    public class HomeController : Controller { public ActionResult Index() { return View(); } }

  4. Create view Index with javascript references: @Url.Content("~/Scripts/jquery-1.6.4.min.js")" "@Url.Content("~/Scripts/jquery.signalR.js")" and function:

    $(function () {
        var hub = $.connection.chatHub;
        hub.AddMessage = function (msg) {
            $('#messages').append('<li>' + msg + '</li>');
        };
        $.connection.hub.start().done(function() {
            $('#send').click(function() {
                hub.send($('#msg').val());
            });
        });
    });    
    
  5. Create class ChatHub:

    public class ChatHub:Hub { public void Send(string message) { Clients.AddMessage(message); } }

like image 115
Kirill Bestemyanov Avatar answered Oct 29 '25 14:10

Kirill Bestemyanov