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?)
You don't have to open multiple connections, just one, but to use
Group
: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
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.
Okay... Here's the simplest way to make multiple rooms:
I have a dropdown list of available rooms, and the selected room will be the value of an element, let's say a textbox:
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: