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
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With