Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - SignalR multiple chat rooms

I am planning to create a chat application, and I've read that SignalR is one of the best technologies to apply.

I've seen examples of it, but they only have a single chat room.

I want to have multiple chat rooms. The user will just choose one of those chat rooms.

Although I'm a beginner, I think to create a single chat room in SignalR is by this:

<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 = single chat room (I'm not sure)

So if I have many connections (for example, connection1, connection2, connection3....) I can have multiple chat rooms?

Once again, I am not sure if this is correct... Please help me on how to implement multiple chat rooms...

(PS: I have seen JABBR, but its code is making my nose bleed. Can you provide simple examples, please?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...