SignalR客户端(Xamarin)向特定用户发送消息时,没有收到消息。

问题描述 投票:0回答:1

我的问题是:我有一个WPF应用程序和一个Xamarin Forms应用程序。我想创建一个聊天程序。当我从WPF调用一个应该向每个用户发送消息的方法时,它可以工作。但当我选择一个特定的用户时,它却不工作。在这种情况下,Xamarin网站上的 "On "方法没有被启动。可能是我在登录用户时搞乱了什么。这是我的代码。

Xamarin

            var hubConnection = new HubConnection("my_url");
            hubConnection.Headers.Add("login", CacheUtils.User.login);

            ChatHubProxy = hubConnection.CreateHubProxy("ChatHub");
            await hubConnection.Start();


            ChatHubProxy.On<string, string>("UpdateChatMessage", (message, username) =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    MessagingCenter.Send(this, "AddMessage", new Message() { Text = message, User = username });
                });
            });               

            string lConnectionId = await ChatHubProxy.Invoke<string>("Login");
            hubConnection.ConnectionId = lConnectionId;

所以我基本上创建了一个连接,并订阅了一个 "On "方法。在头中我传递了一个用户登录。就像我之前说的,当消息是给每个人的时候,接收消息就会工作。在服务器端,我首先调用一个方法 "Login",将用户添加到我的ConcurrentDictionary中。然后在 "SendMessageToSpecificUser "方法中,我从这个字典中得到用户,我调用 "UpdateChatMessage"。

服务器端

    private static ConcurrentDictionary<string, string> clients = new ConcurrentDictionary<string, string>();
    public void SendMessage(string message, string username)
    {
        Clients.All.UpdateChatMessage(message, username); //this works
    }

    public void SendMessageToSpecificUser(string message, string login)
    {
        string lUserId = clients.Where(x => x.Value == login).FirstOrDefault().Key;
        if (!string.IsNullOrEmpty(lUserId))
            Clients.User(lUserId).UpdateChatMessage(message, login); //this doesn't work
    }        

    public string Login()
    {
        string username = Context.Headers.Get("login");
        if (clients.ContainsKey(username))
            ((IDictionary)clients).Remove(username);

        clients.TryAdd(Context.ConnectionId, username);

        return Context.ConnectionId;
    }

感谢任何帮助:)

c# asp.net xamarin.forms signalr
1个回答
1
投票

好吧,我找到了解决方案。我应该使用:

Clients.Client(lUserId).UpdateChatMessage(message, login);

而不是

Clients.User(lUserId).UpdateChatMessage(message, login);

© www.soinside.com 2019 - 2024. All rights reserved.