gpt4 book ai didi

node.js - Socket.io - 无法发送到特定房间,但可以发送到每个人

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:51 25 4
gpt4 key购买 nike

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

背景:在我的服务器代码(server.js)中,一旦有人成功加入房间,我想发出一个事件,告诉该房间中的所有客户端有人加入。

问题:如果我尝试将 .to(room).in(room).emit 结合使用,我不会收到错误,但不会向客户端传输任何内容...但 .emit 会自行工作。

有效方法:我成功地实现了 socket.join() 代码,并在回调中 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);
})
}
})

最佳答案

我成功地解决了这个问题:

不起作用:

socket.join (my_room)

工作:

socket.join (my_room.toString ())

关于node.js - Socket.io - 无法发送到特定房间,但可以发送到每个人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48375426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com