Signalr:当用户为特定用户发送消息时,无法发回消息

本文关键字:消息 用户 Signalr | 更新日期: 2023-09-27 18:33:30

我是使用SignalR的新手。当我向特定用户发送消息时:

  1. 我没有收到消息(我在屏幕上看不到它)。
  2. 用户收到通知后无法发回消息。

这意味着发送消息只能是在一个方向上。如何做到两个用户可以互相发送消息?

我使用我的课程:

[HubName("TSChatHub")]
[Authorize]
public class ChatHub : Hub
{
    private readonly static ConnectionMapping<string> _connections =
        new ConnectionMapping<string>();
    public void SendChatMessage(string who, string message)
    {
        string name = Context.User.Identity.Name;
        foreach (var connectionId in _connections.GetConnections(who))
        {
            Clients.Client(connectionId).addChatMessage(name + ": " + message);
        }
    }
    public override Task OnConnected()
    {
        string name = Context.User.Identity.Name;
        _connections.Add(name, Context.ConnectionId);
        return base.OnConnected();
    }
    public override Task OnDisconnected(bool stopCalled)
    {
        string name = Context.User.Identity.Name;
        _connections.Remove(name, Context.ConnectionId);
        return base.OnDisconnected(stopCalled);
    }
    public override Task OnReconnected()
    {
        string name = Context.User.Identity.Name;
        if (!_connections.GetConnections(name).Contains(Context.ConnectionId))
        {
            _connections.Add(name, Context.ConnectionId);
        }
        return base.OnReconnected();
    }
}
  public class ConnectionMapping<T>
{
    private readonly Dictionary<T, HashSet<string>> _connections =
       new Dictionary<T, HashSet<string>>();
    public int Count
    {
        get
        {
            return _connections.Count;
        }
    }
    public void Add(T key, string connectionId)
    {
        lock (_connections)
        {
            HashSet<string> connections;
            if (!_connections.TryGetValue(key, out connections))
            {
                connections = new HashSet<string>();
                _connections.Add(key, connections);
            }
            lock (connections)
            {
                connections.Add(connectionId);
            }
        }
    }
    public IEnumerable<string> GetConnections(T key)
    {
        HashSet<string> connections;
        if (_connections.TryGetValue(key, out connections))
        {
            return connections;
        }
        return Enumerable.Empty<string>();
    }
    public void Remove(T key, string connectionId)
    {
        lock (_connections)
        {
            HashSet<string> connections;
            if (!_connections.TryGetValue(key, out connections))
            {
                return;
            }
            lock (connections)
            {
                connections.Remove(connectionId);
                if (connections.Count == 0)
                {
                    _connections.Remove(key);
                }
            }
        }
    }
}

有我的观点:

  <div class="chatcontainer">
    <input type="text" id="message" />
    <input type="button" id="sendmessage" value="Send" />
    <input type="hidden" id="displayname" />
    <ul id="discussion">
    </ul>
</div>
 $(function () {
        // Declare a proxy to reference the hub. 
        var chat = $.connection.TSChatHub;
        debugger;
        // Create a function that the hub can call to broadcast messages.
        chat.client.addChatMessage = function (name, message) {
            // Add the message to the page. 
            $('#discussion').append('<li><strong>' + htmlEncode(name)
                + '</strong>:&nbsp;&nbsp;' + htmlEncode(name) + '</li>');
        };
        // Get the user name and store it to prepend to messages.
       // $('#displayname').val(prompt('Enter your name:', ''));
        // Set initial focus to message input box.  
        $('#message').focus();
        // Start the connection.
        $.connection.hub.start().done(function () {
            console.log('Now connected, connection ID=' + $.connection.hub.id);
            $('#sendmessage').click(function () {
                // Call the Send method on the hub. 
                chat.server.sendChatMessage($('#message').val());
                // Clear text box and reset focus for next comment. 
                $('#message').val('').focus();
            });
        }).fail(function () { console.log("Could not connect"); });
    });
 // This optional function html-encodes messages for display in the page.
    function htmlEncode(value) {
        var encodedValue = $('<div />').text(value).html();
        return encodedValue;
    }

任何人都有解决方案可以帮助我

Signalr:当用户为特定用户发送消息时,无法发回消息

如果我

正确理解您,您可以像这样向特定用户发送消息。

public void SendChatMessage(string who, string message)
{
    string name = Context.User.Identity.Name;
    //foreach (var connectionId in _connections.GetConnections(who))
    //{
        //Clients.Client(connectionId).addChatMessage(name + ": " + message);
    //}
    Clients.User(who).addChatMessage(name + ": " + message);
}

而"字符串谁"应该是接收者用户名。希望这有帮助。

只需更改您的addChatMessage方法的参数

 public void SendChatMessage(string who, string message)
    {
        string name = Context.User.Identity.Name;
        foreach (var connectionId in _connections.GetConnections(who))
        {
            Clients.Client(connectionId).addChatMessage(name , message);
        }
    }

这行代码正在调用您在视图上编写的客户端addChatMessage方法

Clients.Client(connectionId).addChatMessage(name , message);

该函数未正确映射,因为您从 cs 页面提供的参数与客户端方法的预期不同。

您的来电

 Clients.Client(connectionId).addChatMessage(name + ": " + message);

客户端方法预期的参数

 chat.client.addChatMessage = function (name, message) 

您正在提供单个参数,因此它没有被映射。

如果问题仍然存在,请尝试在SendChatMessage方法中检查_connections字典,消息不会返回给您的唯一原因是如果您的连接ID未添加到此字典中,这是不可能的,因为这是您在OnConnected事件中运行应用程序后立即发生的第一步