我创建了一个SignalR项目。想要一个像基本whatsapp的应用程序。我可以使用SignalR向所有客户发送消息,但我无法向特定用户发送消息。
这是我尝试过的。
服务器端
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
public class ChatHub : Hub
{
public static string UserName = "";
public void Send(string User, string Message)
{
//It doesn't works
Clients.User(UserName).sendMessage(Message);
//It works
Clients.All.sendMessage(Message);
}
public override Task OnConnected()
{
//It works I get the UserName
UserName = Context.QueryString["UserName"];
return base.OnConnected();
}
}
客户端
protected override async void OnAppearing()
{
chatHubConnection = new HubConnection("http://192.168.2.2:80/", new Dictionary<string, string>{
{ "UserName", myUser }
});
chatHubProxy = chatHubConnection.CreateHubProxy("ChatHub");
chatHubProxy.On<string>("sendMessage", (k) => {
Messages.Add(string.Format("Msg:{0}", k));
});
await chatHubConnection.Start();
}
private async void SendButton_Clicked(object sender, EventArgs e)
{
await chatHubProxy.Invoke<string>("Send", recieverEntry.Text, messageEntry.Text);
}
答案 0 :(得分:2)
使用ConnectionId将消息发送到特定客户端。 UserId和UserName是不同的东西,更多细节 - https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/mapping-users-to-connections
将您的代码更改为以下(理想情况下,此Connections字典应作为单独的类提取,以处理用户名到连接映射)
public class ChatHub : Hub
{
public static ConcurrentDictionary<string, string> Connections = new ConcurrentDictionary<string, string>();
public void Send(string username, string message)
{
string connectionToSendMessage;
Connections.TryGetValue(username, out connectionToSendMessage);
if (!string.IsNullOrWhiteSpace(connectionToSendMessage))
{
Clients.Client(connectionToSendMessage).SendMessage(message);
}
}
public override Task OnConnected()
{
if (!Connections.ContainsKey(Context.ConnectionId))
{
Connections.TryAdd(Context.QueryString["UserName"], Context.ConnectionId);
}
return base.OnConnected();
}
}