简体   繁体   English

Socket.io - 不能发射到特定房间,但可以发射给每个人

[英]Socket.io - Cannot emit to a specific room but can emit to everyone

I am using Socket.io 2.0.4 and React.js (CRA)我正在使用Socket.io 2.0.4React.js (CRA)

Background: In my server code (server.js) once someone sucessfully joins a room I want to emit an event that tells all clients in that room that someone joined.背景:在我的服务器代码 (server.js) 中,一旦有人成功加入一个房间,我想发出一个事件,告诉该房间中的所有客户端有人加入。

Problem: I don't get an error but nothing get's transmitted to my client if I try to use .to(room) or .in(room) in conjuction with .emit ... but .emit will work on it's own.问题:如果我尝试将.to(room).in(room).emit结合使用,我没有收到错误,但没有任何信息传输给我的客户……但.emit会自行工作。

What Works: I am successfully able to implement to the socket.join() code and in the callback I console.log the IDs of each person that's joined using the showClients function I created.什么有效:我能够成功地实现socket.join()代码,并在回调中我 console.log 使用我创建的showClients函数加入的每个人的 ID。 I can see each person join one at a time via console.我可以通过控制台看到每个人一次加入一个。

Notes: I store the room name in the data variable and access it using data.room but I've also just wrote in the room name manually to no avail.注意:我将房间名称存储在 data 变量中并使用data.room访问它,但我也只是手动写入房间名称无济于事。

Client Code (abridged)客户代码(节略)

import React, {Component} from 'react';
import Card from '../card/card';
import './game.css';

const io = require('socket.io-client');
const socket = io()  

class Game extends Component {

    constructor(props){
        super();
    }

componentDidMount(){
        this.gameCode();
        this.cardSelected();

        socket.on("cardDiscarded", this.updateDiscard);

        socket.on("playerJoined", () => {
            alert("hi!");
            console.log("YAY!!!!!!!!!!!!!!!!!!!!");
        });
    }
   //....rest of my code....
}

Server Code (abridged)服务器代码(节略)

Look at the joinRoom function to see the issuejoinRoom函数看看问题

const express = require('express');

const app = express();
const port = process.env.PORT || 5000;

const http = require("http").Server(app);
var io = require("socket.io")(http);

var bodyParser = require('body-parser');

console.log("Hello world!");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

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

    socket.on("createNewRoom", (name) =>{
        CreateNewRoom();
        console.log("NEW ROOM CREATED!");
    })

    socket.on("joinRoomRequest", (name, room) =>{
        // console.log(name, room);
        console.log("Request to join room");
        var data = {
            name: name,
            room: room
        };
        joinRoom(data);
    })


    function CreateNewRoom() {
        //Get unique room number
        var thisGameId = (Math.random() * 1000000 ) | 0;

        //Send the room number to the browser
        socket.emit('newRoomCreated', {roomID: thisGameId, mySocketID: socket.id});
        //Tell socket.io this user is joining this room
        socket.join(thisGameId.toString());
        console.log(thisGameId);
    };

    function joinRoom(data){
        console.log("trying to join room:" + data.room);
        data.socketID = socket.id;
        console.log(data);
        socket.join(data.room, () => {
            let rooms = Object.keys(socket.rooms);
            //Let the clients know a player has joined
            console.log(rooms);
            console.log(data.name + " JOINED room " + data.room);
            showClients(data.room);
            io.to(data.room).emit("playerJoined");  //<----- DOESN't WORK
        });
    }

    function showClients(room){
        var roomClients = io.of('/').in(room).clients((err, data)=>{
            if (err) throw err;
            console.log("The people in room ", room, " are: ", data);
        })
    }
})

I believe io.in(room).emit(data) is what you are looking for.我相信io.in(room).emit(data)是你正在寻找的。 I recently ran into this problem as well.我最近也遇到了这个问题。 According to the documentation, if you want to emit to everyone accept 'socket' (aka the user who joined) you use socket.to(room).emit .根据文档,如果您想向所有人发出接受“socket”(即加入的用户)的信息,请使用socket.to(room).emit If you want to emit to everyone including the user, you use io.in(room).emit如果您想向包括用户在内的所有人发送,请使用io.in(room).emit

I managed to solve it like this:我设法解决它是这样的:

does not work:不起作用:

socket.join (my_room)

work:工作:

socket.join (my_room.toString ())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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