Issue with socket.io join room

I have a issue with socket.io with rooms.

See the server code:

This code below is working properly.

io.on('connection', function(socket){

 socket.join("myroom");

 socket.on('chat message', function(data){
  io.in("myroom").emit('chat message', data);
 });


});

But I want the user to enter the room after an event. Like the code below.

io.on('connection', function(socket){

 socket.on('chat message', function(data){
  io.in("myroom").emit('chat message', data);
 });

 socket.on('join', function(name, device, room){
   socket.join("myroom");
 });


});

It's almost the same code , but does not work. What am I doing wrong?

The event is being called correctly.

Edit. Added the front-end code:

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



   $('#msg_form').submit(function(){
     socket.emit('chat message', $("#m").val(), "myroom");
     $('#m').val('');
     return false;
   });

   $("#user").submit(function() {
      var name = $("#name").val();
      var room = $("#room").val();
      var device = navigator.userAgent;

      if (name === "" || name.length < 2) {
        $("#errors").empty();
        $("#errors").append("Please enter a name");
        $("#errors").show();
      } else {
        socket.emit("join", name, device, room);
        $("#messages").focus();
      }
    });

Thank you.



Read more here: https://stackoverflow.com/questions/34350981/issue-with-socket-io-join-room

Content Attribution

This content was originally published by Huro Moto at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: