简体   繁体   中英

Why does socket.io not join a given room?

I'm having problems when I try to join a socket to a room. The name of the room is the socket.id and it is assigned when it is connected. But when this happens it doesn't join to room. What could be the error?

Client code:

var socket = io();

socket.on("connect", function() {
    socket.emit("joinRoom", socket.id);
});

socket.on("agentMessage", function(msg) {
    $('#messages').append("<div class='agent-messages'><p>" + msg + "</p></div>");
});

Server code:

io.on("connection", (socket) => {
   let roomID;

    socket.on("joinRoom", (socket_id) => {
        roomID = socket_id;
        socket.join(roomID);
        socket.to(roomID).emit("agentMessage", "Welcome!");
    });

    socket.on("disconnect", () => {
        socket.leave(socket_id);
    });
});

Your client is actually joining the room , but it is not sending the message . As you are sending message from the server side you cannot send it using the socket , as socket represents a client connection and cannot throw events on behalf of server . You have to use

  io.to(roomID).emit("agentMessage", "Welcome!");

as io represents a server instance and can throw events on behalf of server(actually it is the server). 在此处输入图片说明

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM