简体   繁体   中英

Creating multiple hubs dynamically using SignalR

I am currently using SignalR for chat. I have a form and the user will load a specific order into the form. The scenario is that other staff members may search that order number and therefore i want only those people to be in the chat. Currently if you load the site everyone is in a single hub called ChatHub .

ChatHub.cs:

public class ChatHub: Hub {
 public void Send(string name, string message) {
  // Call the addNewMessageToPage method to update clients.
  Clients.All.addNewMessageToPage(name, message);
 }
}
}

Chat.cshtml:

@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.0.3.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.-->
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.
            var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page.
                $('#discussion').append(htmlEncode(name)
                    + ':' + htmlEncode(message) + '\n');
            };
            // 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 () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}
<script>

I have tried to add the following:

<script>
$(function () {
    var chat = jQuery.connection.chat;

    chat.addMessage = function (message, room) {

        if ($('#currentRoom').val() == room) {
            $('#messagesList').append(message);
        }
    };


        chat.send($('#textboxMessage').val(), $('#currentRoom').val());
        $('#textboxMessage').val("");


    $.connection.hub.start();
});
</script>

I am trying to work out a way of getting multiple hubs or chat rooms based on a user loading an order.

You have to put the users into groups according to the opened order id, change the hub and add a method as below:

public class ChatHub: Hub {
 public void Send(string name, string message,string orderId) {
  // Call the addNewMessageToPage method to update clients.
  Clients.Group(orderId).addNewMessageToPage(name, message);
 }

public void JoinOrderGroup(string name,string orderId)
 {
     Groups.Add(Context.ConnectionId, orderId);
 }
}

Then modify your JavaScript to call the `JoinOrderGroup' when the user opens the page.

@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.0.3.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.-->
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.
             var orderId = '@Model.Id' //You can change this line to get the orderId from the correct place
             var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page.
                $('#discussion').append(htmlEncode(name)
                    + ':' + htmlEncode(message) + '\n');
            };
            // 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 () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                  chat.server.joinOrderGroup($('#displayname').val(),orderId);
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}
<script>

This way, when the page starts and the hub connects, it will send a message to join the group related to the order in the form, and all successive calls to teh send message method will include the order id and it will be propagated to the users in this order only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM