带有不同聊天室的SignalR

时间:2017-10-30 15:22:16

标签: c# .net signalr

我得到锻炼,我需要与SingalR建立一个聊天室,我在其中写下消息和两个聊天室,在按钮的开关上,我决定将广播消息的房间,我对此很新SingalR的东西,虽然我想在这方面得到帮助,这是我到目前为止所做的

public class ChatHub : Hub
    {


        public void Send(string name, string message, string connID)
        {
            // Call the broadcastMessage method to update clients.
            //  Clients.All.broadcastMessage(name, message);
          //  Clients.All.addNewMessageToPage(name, message);

            Clients.Client(connID).broadcastMessage(name, message);
        }

    }

// cshtml视图

@{
    ViewBag.Title = "Chat";
}
<h2>Chat</h2>
<div class="container">
    <input type="text" id="message" />
    <input type="button" id="sendmessage" value="Send" />
    <input type="radio"  id="family" value="family" /> Family
    <input type="radio" id="friends" value="friends" /> Friends
    <input type="hidden" id="displayname" />
    <ul id="discussion"></ul>
</div>
@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.2.2.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('<li><strong>' + htmlEncode(name)
                    + '</strong>: ' + htmlEncode(message) + '</li>');
            };

            chat.client.
            // 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(), $.connection.hub.id);
                    // 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>

0 个答案:

没有答案