I am writing a chat application. I use Angular 6
and .Net Core 3.1.
I have read a lot of documents but still do not understand where there is an error.
My Hub Class
public class ChatHub : Hub
{
private static List<ConnectedUser> _connectedUsers = new List<ConnectedUser>();
public override Task OnConnectedAsync()
{
var username = Context.GetHttpContext().Request.Query["username"];
var status = _connectedUsers.FirstOrDefault(x => x.Username == username);
if (status == null)
{
_connectedUsers.Add(new ConnectedUser
{
ConnId = Context.ConnectionId,
Username = username
});
}
return base.OnConnectedAsync();
}
...
I have a list that keeps the connection id
information of the users connected in my Hub Class
. When users connect, I add to this list.
I operate in my Private Chat Function
below.
public void PrivateChat(string toUser,string fromUser,string message)
{
_connectedUsers.ForEach(val =>
{
if(val.Username == toUser)
Clients.User(val.ConnId).SendAsync("receiveMessage", message,fromUser);
});
}
However, I cannot return to the user I want.
You use it in Angular
this way
this._hubConnection.on('receiveMessage', (message,fromUser) => {
console.log(message , "+" , fromUser);
}
);
You should use
Clients.Clients(val.ConnId).SendAsync("receiveMessage", message,fromUser);