Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using signalr with one to one including offline modus

I am trying to implement a chat, from one client to another client. While searching I came across the interesting SignalR library, used for server push actions.

Say a client sends another client a message, but that client is offline at the moment. When he comes back online he should see a notification that he has received a message while he was offline. Does SignalR store its conversations somewhere? How can I store conversations in my database? How can I make the client see a notification when he has received an offline message?

Can anyone provide me with such a tutorial? I only found tutorials with online-online chat.

Kind regards

like image 249
devqon Avatar asked Feb 17 '14 18:02

devqon


1 Answers

SignalR does not provide offline messaging by itself.

You will have to store the offline messages in a database or somewhere and provide the logic to notify the users for the pending messages.

A naïve implementation:

public class ClientHub : Hub
{
    public SendMessage(string message, string targetUserName)
    {
        var userName = Context.User.Identity.Name;
        if (HubHelper.IsConnected(targetUserName))
        {
            Clients.User(targetUserName).sendMessage(message);
        }
        else
        {
            DataAccess.InsertPendingMessage(userName, targetUserName, message);
        }
    }

    public SendPendingMessages()
    {
            // Get pending messages for user and send it
            var meesages = DataAccess.GetPendingMessages(userName);
            Clients.User(userName).processPendingMessages(messages);    
    }

    public override Task OnConnected()
    {
        var connected = base.OnConnected();
        var userName = Context.User.Identity.Name;
        if (!string.IsNullOrWhiteSpace(userName))
        {
            HubHelper.RegisterClient(userName, Context.ConnectionId);
            SendPendingMessages();
        }
        return connected;
    }
}

This code assumes the following is implemented:

  • Client function sendMessage to show a private message
  • Client function processPendingMessages to show all the pending messages
  • DataAccess object with methods to Get (GetPendingMessages) and Insert (InsertPendingMessage) pending messages.
  • Helper class HubHelper to maintain the current client connections in memory.
like image 96
thepirat000 Avatar answered Sep 22 '22 13:09

thepirat000