Javascript Socket.io-知道插座位于哪个房间

Javascript Socket.io-知道插座位于哪个房间,javascript,node.js,sockets,websocket,socket.io,Javascript,Node.js,Sockets,Websocket,Socket.io,我正在用node.js服务器在socket.io上编写一个简单的聊天。所以我需要知道插座在哪个房间。例如,插座已连接并加入房间。因此,当这个套接字发送一条消息时,我只想将它广播到该房间中的套接字(sck.broadcast.to(it_room.emit)) 我不需要一系列插座和它们的相关信息(在哪个房间等)。尝试以下方法,但我不确定它是否在所有情况下都能工作 Object.keys(sck.manager.roomClients[sck.id])[1] 我通过记录socket发现了这一点,然

我正在用node.js服务器在socket.io上编写一个简单的聊天。所以我需要知道插座在哪个房间。例如,插座已连接并加入房间。因此,当这个套接字发送一条消息时,我只想将它广播到该房间中的套接字(sck.broadcast.to(it_room.emit))


我不需要一系列插座和它们的相关信息(在哪个房间等)。

尝试以下方法,但我不确定它是否在所有情况下都能工作

Object.keys(sck.manager.roomClients[sck.id])[1]
我通过记录socket发现了这一点,然后我查找了房间信息,并以您可以在我的代码中看到的方式将其提取出来



我使用的是0.9.6 socket.io版本,最新版本可能有不同的解决方案。

首先输入您的用户名和加入的聊天室。提交表单后,用户名和房间信息将作为查询字符串附加到URL。在浏览器中:location.search:这是我们访问查询字符串的方式。我们必须解析它

将此CDN添加到main.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/qs/6.6.0/qs.min.js"></script>
{ignoreQueryPrefix:true}此选项将从查询字符串中省略“?”

一旦您达到用户名和房间名称,我们就可以从客户端发出事件

client.js

socket.emit('join', { username, room }, (error) => {
    if (error) {
        alert(error)
        location.href = '/' //will keep the client in the same url
    }
})
现在我们要从服务器端听这个事件。但我们必须跟踪用户

index.js

io.on("connection", socket => {

  socket.on("join", ({ username, room }, callback) => {
    //we have to define addUser function


let users = [];

const addUser = ({ id, username, room }) => {
  // Clean the data
  username = username.trim().toLowerCase();
  room = room.trim().toLowerCase();

  // Validate the data
  if (!username || !room) {
    return {
      error: "Username and room are required!"
    };
  }

  // Check for existing user
  const existingUser = users.find(user => {
    return user.room === room && user.username === username;
  });

  // Validate username
  if (existingUser) {
    return {
      error: "Username is in use!"
    };
  }

  // Store user
  const user = { id, username, room };
  users.push(user);
  // users=users.push(user) this will cause error
  return { user };
};
//as you see this function will return either error or user object

//Socket generates an id upon connection.
//result is either error or user
    const { error, user } = addUser({ id: socket.id, username, room });

    if (error) {
      return callback(error);
    }

    socket.join(user.room);//socket joined to this room
    //now time to emit a new event
    socket.emit("message", ( "Welcome!"));
    socket.broadcast
      .to(user.room)
      .emit(
        "message",
        (`${user.username} has joined!`)
      );


//broadcast will send messages to everyone in the chat room except the connected socket

    callback(); //success scenario. let the client knows that it is allowed to connect
  })   
})
socket.emit('join', { username, room }, (error) => {
    if (error) {
        alert(error)
        location.href = '/' //will keep the client in the same url
    }
})
io.on("connection", socket => {

  socket.on("join", ({ username, room }, callback) => {
    //we have to define addUser function


let users = [];

const addUser = ({ id, username, room }) => {
  // Clean the data
  username = username.trim().toLowerCase();
  room = room.trim().toLowerCase();

  // Validate the data
  if (!username || !room) {
    return {
      error: "Username and room are required!"
    };
  }

  // Check for existing user
  const existingUser = users.find(user => {
    return user.room === room && user.username === username;
  });

  // Validate username
  if (existingUser) {
    return {
      error: "Username is in use!"
    };
  }

  // Store user
  const user = { id, username, room };
  users.push(user);
  // users=users.push(user) this will cause error
  return { user };
};
//as you see this function will return either error or user object

//Socket generates an id upon connection.
//result is either error or user
    const { error, user } = addUser({ id: socket.id, username, room });

    if (error) {
      return callback(error);
    }

    socket.join(user.room);//socket joined to this room
    //now time to emit a new event
    socket.emit("message", ( "Welcome!"));
    socket.broadcast
      .to(user.room)
      .emit(
        "message",
        (`${user.username} has joined!`)
      );


//broadcast will send messages to everyone in the chat room except the connected socket

    callback(); //success scenario. let the client knows that it is allowed to connect
  })   
})