Как получить идентификатор соединения клиента signalR на стороне сервера?

мне нужно получить идентификатор соединения клиента. Я знаю, что вы можете получить его со стороны клиента, используя $.connection.hub.id. Мне нужно войти в веб-службу, которая обновляет записи в базе данных, в свою очередь отображая обновление на веб-странице. Я новичок в signalR и stackoverflow, поэтому любые советы будут оценены. На моей клиентской веб-странице у меня есть это:

<script type="text/javascript">
    $(function () {
        // Declare a proxy to reference the hub. 
        var notify = $.connection.notificationHub;

        // Create a function that the hub can call to broadcast messages.
        notify.client.broadcastMessage = function (message) {
            var encodedMsg = $('<div />').text(message).html();// Html encode display message.
            $('#notificationMessageDisplay').append(encodedMsg);// Add the message to the page.
        };//end broadcastMessage

        // Start the connection.
        $.connection.hub.start().done(function () {
            $('#btnUpdate').click(function () {
                //call showNotification method on hub
                notify.server.showNotification($.connection.hub.id, "TEST status");
            });
        });


    });//End Main function


</script>

все работает, пока я не хочу обновить страницу с помощью signalR. Функция show notification в моем концентраторе это:

//hub function
public void showNotification(string connectionId, string newStatus){               
    IHubContext context = GlobalHost.ConnectionManager.GetHubContext<notificationHub>();
    string connection = "Your connection ID is : " + connectionId;//display for testing
    string statusUpdate = "The current status of your request is: " + newStatus;//to be displayed
    //for testing, you can display the connectionId in the broadcast message
    context.Clients.Client(connectionId).broadcastMessage(connection + " " + statusUpdate);
}//end show notification

как я могу отправить connectionid в мой веб-сервис?

надеюсь, я не пытаюсь сделать что-то невозможное. Спасибо заранее.

2 ответов


когда клиент вызывает функцию на стороне сервера, вы можете получить их идентификатор соединения через Context.ConnectionId. Теперь, если вы хотите получить доступ к этому идентификатору соединения через механизм вне концентратора, вы можете:

  1. просто попросите концентратор вызвать внешний метод, передающий идентификатор соединения.
  2. управление списком подключенных клиентов он же вроде public static ConcurrentDictionary<string, MyUserType>... путем добавления в словарь в OnConnected и удаление из него в OnDisconnected. После того, как у вас есть список пользователей, вы можете запросите его через внешний механизм.

Ex 1:

public class MyHub : Hub
{
    public void AHubMethod(string message)
    {
        MyExternalSingleton.InvokeAMethod(Context.ConnectionId); // Send the current clients connection id to your external service
    }
}

Ex 2:

public class MyHub : Hub
{
    public static ConcurrentDictionary<string, MyUserType> MyUsers = new ConcurrentDictionary<string, MyUserType>();

    public override Task OnConnected()
    {
        MyUsers.TryAdd(Context.ConnectionId, new MyUserType() { ConnectionId = Context.ConnectionId });
        return base.OnConnected();
    }

    public override Task OnDisconnected(bool stopCalled)
    {
        MyUserType garbage;

        MyUsers.TryRemove(Context.ConnectionId, out garbage);

        return base.OnDisconnected(stopCalled);
    }

    public void PushData(){
        //Values is copy-on-read but Clients.Clients expects IList, hence ToList()
        Clients.Clients(MyUsers.Keys.ToList()).ClientBoundEvent(data);
    }
}

public class MyUserType
{
    public string ConnectionId { get; set; }
    // Can have whatever you want here
}

// Your external procedure then has access to all users via MyHub.MyUsers

надеюсь, что это помогает!


Я позволю себе не согласиться на повторное подключение. Клиент остается в списке, но connectid изменится. Я делаю обновление статического списка при повторном подключении, чтобы решить эту проблему.