1

so there is my code i am trying to create chatroom with Socket.io with rooms (one-to-one random chatroom) but i think there is bug because when i connect first two sockets it works perfectly but when i connect third socket it does not work anymore i think it is because of "numb++" but i don't know how to correct it because i have not many experience in rooms. i wanna implement : chat between 2 socket and when third client joins i wanna create second room and wait for forth socket to join to chat and etc. , and u i know i wanna one to one random chatroom like Omegle.

 var numb = 1;
 var chnm = io.of('/STchat')

 app.get('/STchat', function(req, res){

res.sendFile('C:\\Users\\tuna\\Desktop\\JUSTFOL\\views\\Tchat.html')

chnm.once('connect', function(socket){
  socket.join("room" + numb)
  console.log('made socket connection', socket.id);
chnm.in("room" + numb).clients(function(err, clients){
      if(clients.length > 2) {

     numb++
      }
});
socket.on('chat', function(data) {
 chnm.in("room" + numb).emit('chat',data)

  })
  socket.on('disconnect', function(){
    console.log('socket disconnected')
  });

}
});
app.get('/StvChat', function(req ,res){
res.sendFile(__dirname + '/views/VideoC.html');


});









var socket = io.connect('http://localhost:5000/STchat')

var message = document.getElementById('message');
handle = document.getElementById('handle');
btn = document.getElementById('send');
output = document.getElementById('output');
typing = document.createElement('p');
typing.className = "tycl";
input = document.getElementById("message");

$('form').submit(function(){


    socket.emit('chat',{
        message: message.value,

    });
    $('#message').val('');
    return false;
});
input.addEventListener("keyup", function(event) {
       event.preventDefault();

    if (event.keyCode === 13) {

      document.getElementById("send").click();
    }
  });

socket.on('chat', function(data){
  output.innerHTML += '<p>' +'  '+ data.message +'</p>' 
});
iLiA
  • 3,053
  • 4
  • 23
  • 45
  • One thing I noticed while looking over your code is that you have ```if(clients.length > 2)```. Shouldn't this be ```>= 2```? Otherwise numb will not increment until three users join. – James Pooley Oct 29 '18 at 11:46
  • so i understand that and that is reason of that i am not able to text when third socket connects? as u know when first 2 socket connect they can text with each other but when third connects nobody can text with each other including first 2 socket – iLiA Oct 29 '18 at 14:17
  • i tried this but now only first socket can emit text but when second socket connects , first socket is not able to send text anymore , second third and etc. too – iLiA Oct 29 '18 at 14:21
  • Another problem I see that is likely breaking the chat is this line: ```chnm.in("room" + numb).emit('chat',data)``` When a chat event is emitted, you are emitting to whatever value numb currently is. That wont work, because numb will be changing constantly. You will need to do one of two options. Either track what user (by their socket.id) is in what room via an array or database, or implement a method to determine what room the user is in like this solution https://stackoverflow.com/a/45315446/9436750. So, on chat event, get the users current room by their socket.id, and then emit that room – James Pooley Oct 29 '18 at 14:31
  • literally i did not understand what u mean in " you are emitting to whatever value numb currently is" otherwise, if i create the array of socket ids it will cause traffic and server will hang up because if many socket connects at same time code will not be able to splice the array , i thought about that algorithm but that is the best one i get so i prefer that , i will be very glad if u explain the text i wrote above thanks – iLiA Oct 29 '18 at 18:50

1 Answers1

1

This was too long to fit in the comments so I have added as an answer. To clarify, here is an issue I am seeing in the way you are emitting the chat event. Lets walk through a scenario.

var numb = 1;

Two users (User A, and User B) connect to the socket and are put into room "room1". Now, numb should be incremented by your code and now numb will be == 2.

Now, User A (who is in "room1") emits a "chat" event. Here is the issue I see:

socket.on('chat', function(data) {
    chnm.in("room" + numb).emit('chat', data)

})

User A's chat event is emitted to "room2" but User A is in "room1". This happens because numb == 2 at this point in the scenario and you are using numb to emit that event, basically this is what happens chnm.in("room" + 2). User B does not get User A's emit, because it was sent to the wrong room (room2). If I misunderstood what you are trying to do please let me know.

EDIT: As requested here is some modifications to your code that I have tested locally with success. Two users per each room.

var numb = 1;
var chnm = io.of('/STchat');

app.get('/STchat', function(req, res) {

    res.sendFile('C:\\Users\\tuna\\Desktop\\JUSTFOL\\views\\Tchat.html');

    chnm.once('connect', function(socket) {

        // store the room in a var for convenience
        var room = "room" + numb;

        // join socket to the next open room
        socket.join(room);

        // store room on socket obj for use later - IMPORTANT
        socket.current_room = room;

        // log some stuff for testing
        console.log('made socket connection', socket.id);
        console.log("Joined room: ", socket.current_room);

        // Check room occupancy, increment if 2 or more
        chnm.in(room).clients(function(err, clients) {
            if (clients.length >= 2) {
                numb++;
            }
        });

        socket.on('chat', function(data) {
            // emit to that sockets room, now we use that current_room
            chnm.in(socket.current_room).emit('chat', data);
        });

        socket.on('disconnect', function() {
            console.log('socket disconnected');
        });
    });

});

app.get('/StvChat', function(req, res) {
    res.sendFile(__dirname + '/views/VideoC.html');
});
James Pooley
  • 607
  • 4
  • 17
  • oh i understood my bug and know but now i am thinkin' bout how User A and User B can text in each other? – iLiA Oct 29 '18 at 19:26
  • when i run my code first 2 socket can chat in each other (User A and User B) and how can it be done when in my code there is written to emit in room2 ? and they are in room1 :/ – iLiA Oct 29 '18 at 19:27
  • There are different ways to do this. What you need to know is, what room is that user in. I mentioned some possibilities earlier. The way I do it is using a realtime database (RethinkDb) to keep track of which room each user is in based on the socket.id. I store other data on the user so this solution made the most sense for me. You can also keep track of the data in some type of array if you choose but that can be more of a pain to manage when you have many users at once. The third option is using that solution I shared previously, iterating through the rooms objects and splicing. – James Pooley Oct 29 '18 at 19:33
  • oh no u haven't understood correctly , i mean if there is that kinda bug how code can still emit chat in first two sockets :D – iLiA Oct 29 '18 at 19:51
  • Once a third or fourth person connects it stops working though, correct? Because your code does not increase numb to 2 until a third user connects – James Pooley Oct 29 '18 at 19:56
  • soo then if numb will increase when third user connects what is problem, sorry but can u show me a code demo? because it is not understandable i think , if i bother u OK i will understand – iLiA Oct 30 '18 at 11:36
  • I modified your code and edited/added it to my answer. I tested it locally. It is working for me, I tested 4 users, the first two users joined room1, the second two users joined room2. They were able to chat independently to their own room. – James Pooley Oct 30 '18 at 12:41