Reputation: 33
I've to create a Chat between two users (a hired person and a hirer). It doesn't need to be real-time but using SignalR I might accomplish that, but no problem.
I'll store the previous messages on a database to retrieve everytime the chat was open.
So, I need to broadcast a message only between two users, but, a user can have multiple chat rooms with differente people (but only 1:1).
How can I accomplish that logic in my code? Do I have to use Groups? And if so, how can I store the information that "this user has to send message to that user", on a 1:1 chat, and not broadcast to everyone?
My ChatHub class:
public class ChatHub : Hub
{
private readonly IChatAppService _chatAppService;
public ChatHub(IChatAppService chatAppService)
{
_chatAppService = chatAppService;
}
public string GetConnectionId()
{
return Context.ConnectionId;
}
public async Task SendMessage(ChatAddVM message, string userName)
{
string connectionId = GetConnectionId();
await Clients.Client(connectionId).SendAsync("broadcastMessage", userName, message.Message);
//USED TO SAVE THE MESSAGE ON DB
await _chatAppService.CreateMessage(message);
}
}
Upvotes: 2
Views: 3333
Reputation: 20082
For this question
how can I store the information that "this user has to send message to that user", on a 1:1 chat, and not broadcast to everyone?
I think you can store into db the information like from which user to which user had chat. Because you already store previous message between user with user so I think you can do the same like that
Also to send message between 1:1 I write small blog here so you can take a look at
The idea is every user have 1 connection id so we need to store the connection id of the user in the memory to send message from 1 to 1
Upvotes: 0