Using signalr with one to one, including standalone modus

I am trying to chat from one client to another client. During the search, I came across an interesting SignalR library used for push server actions.

Say a client sends a message to another client, but this client is not working right now. When he returns to the Internet, he should see a notification that he received a message when he was offline. Somewhere, somewhere, does SignalR store its conversations? How to store conversations in my database? How can I make a client see a notification when they receive a message offline?

Can someone provide me with such a tutorial? I just found tutorials with online online chat.

Yours faithfully

+4
source share
1 answer

SignalR does not provide offline messages on its own.

You will need to store offline messages in a database or somewhere and provide logic to notify users of pending messages.

Naive 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 that the following is implemented:

  • SendMessage client function for displaying a private message
  • Client function processPendingMessages to display all pending messages
  • A DataAccess object with GetPendingMessages and InsertPendingMessage pending messages.
  • HubHelper helper class to support current in-memory client connections.
+11
source

Source: https://habr.com/ru/post/1527360/


All Articles