SignalR multiple chat rooms

三世轮回 提交于 2019-12-02 19:45:29
Hatake Kakashi

You don't have to open multiple connections, just one, but to use 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);
    }
}

One group means one room, so every time one user joins one room, you just add that user to the group of that room, and when you want to broadcast message, just send the message to the clients in the group.

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

raberana

Okay... Here's the simplest way to make multiple rooms:

$(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);
   }
}

I have a dropdown list of available rooms, and the selected room will be the value of an element, let's say a textbox:

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

Now, every time .send is called, we will pass not just the message, but also the current room...

The .addMessage will return two values to every client, one is the message, the other is a room... Now we will compare the returned 'room' to the current room of the client. Once they match, the message will be displayed in that current room:

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

You do not need multiple connections. Just use one and put the meta data in the returned JSON message as to which room the message is for. The JavaScript code then needs to direct the message into the correct room.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!