Multiple Chat Rooms SignalR

I plan to create a chat application, and I read that SignalR is one of the best technologies to apply.

I have seen examples of this, but they only have one chat.

I want to have some chats. The user will simply select one of these chats.

Although I'm new, I think you can create a single chat room in SignalR as follows:

<script type="text/javascript">
    $(function () {
        var connection = $.connection.communicator;
        connection.receive = function (from, msg) {
            $("#chatWindow").append("<li>" + from + ": " + msg + "</li>");
        };
        $.connection.hub.start();

        $("#btnSend").click(function () {
            connection.broadcast($("#txtName").val(), $("#txtMsg").val());
        });
    });
</script>

var connection = separate chat (I'm not sure)

So, if I have many connections (e.g. connection1, connection2, connection3 ....), can I have several chats?

Once again, I'm not sure if this is correct ... Please help me on how to implement some chats ...

(PS: I saw JABBR, but its code changes nose. Can you provide simple examples, please?)

+5
3

, , Group:

public class MyHub : Hub, IDisconnect
{
    public Task Join()
    {
        return Groups.Add(Context.ConnectionId, "foo");
    }

    public Task Send(string message)
    {
        return Clients["foo"].addMessage(message);
    }

    public Task Disconnect()
    {
        return Clients["foo"].leave(Context.ConnectionId);
    }
}

, , , , , .

: https://github.com/SignalR/SignalR/wiki/Hubs

+14

... :

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

    chat.addMessage = function (message, room) {

        if ($('#currentRoom').val() == room) {
            $('#messagesList').append('<li>' + message + '</li>');
        }
    };

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

    $.connection.hub.start();
});


public class Chat : Hub
{
   public void Send(string msg, string room)
   {
       Clients.addMessage(msg, room);
   }
}

, , , :

 <input type="text" readonly="readonly" id="currentRoom" />

, , .send, , ...

.addMessage , - , - ... "" . , :

if ($('#currentRoom').val() == room) {
    $('#messagesList').append('<li>' + message + '</li>');
}
+1

You do not need multiple connections. Just use one and put the metadata in the returned JSON message about which room to post to. Then the JavaScript code should direct the message to the right room.

-1
source

All Articles