Socket.io - 无法发射到特定房间但可以向所有人发射

时间:2018-01-22 05:55:29

标签: node.js socket.io

我正在使用Socket.io 2.0.4React.js (CRA)

后台:在我的服务器代码(server.js)中,当有人成功加入一个房间时,我想发出一个事件,告诉该房间内所有客户都有人加入。

问题:我没有收到错误,但如果我尝试将.to(room).in(room).emit结合使用,则无法将任何内容传输到我的客户端......但是.emit会自行完成。

什么有效:我已成功实现socket.join()代码和回调I console.log使用showClients函数加入的每个人的ID我建立。我可以看到每个人通过控制台一次加入一个。

注意:我将房间名称存储在数据变量中并使用data.room访问它,但我也只是手动写入房间名称无效。

客户代码(删节)

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....
}

服务器代码(删节)

查看joinRoom功能以查看问题

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);
        })
    }
})

2 个答案:

答案 0 :(得分:2)

我设法解决了这个问题:

不起作用:

socket.join (my_room)

工作:

socket.join (my_room.toString ())

答案 1 :(得分:0)

我相信io.in(room).emit(data)正是您所寻找的。我最近也遇到了这个问题。根据文档,如果你想向所有人发出接受'socket'(也就是加入的用户),你使用socket.to(room).emit。如果要向包括用户在内的所有人发送,请使用io.in(room).emit