我有一个客户端测试功能,该功能将测试对象发送到socket.io服务器,该服务器的工作是等待客户端事件,然后将数据发送到原始客户端发出的房间中的每个客户端。事件来自。但是,只有原始客户端正在从服务器接收事件。房间中的其他客户端没有收到它。
我已经尝试了io.in(room).emit()
和io.to(room).emit()
服务器端。两个客户肯定会加入同一个房间。服务器也从原始客户端接收事件。
Server.js:
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io").listen(server);
const port = process.env.PORT || 3000;
io.on("connection", socket => {
console.log("user connected: " + socket.id);
socket.on("test", test => {
console.log("received from client, emitting to room: " + test.room);
// io.to(test.room).emit("test", {key: "property from server"}
// io.in(test.room).emit("test", {key: property from server"}
})
})
server.listen(port, () => {
console.log("server running on port: " + port);
});
父项:
const socket = io("http://172.31.99.250:3000");
export default class Lobby extends React.Component {
constructor(props) {
super(props);
this.state = {
username: "",
queue: [],
playerOne: null,
playerTwo: null,
currentMove: "",
matchFound: false,
room: null
};
}
componentDidMount() {
this.joinLobby();
}
joinLobby() {
socket.emit("findMatch() )
socket.on("matchFound", data => {
this.setState({
currentMove: data.currentMove,
playerOne: data.p1,
playerTwo: data.p2,
matchFound: true,
room: data.gameId
});
});
render() {
return this.state.matchFound == true ? (
<ChildComponent
room={this.state.room}
socket={socket}
/>
);
}
}
子组件:
export default class GameBoard extends Component {
constructor(props) {
super(props);
this.state = {
inProgress: true,
msg: null
}
componentDidMount() {
alert("Room ID: " + this.props.room);
}
onTest = () => {
this.props.socket.emit("test", {
testKey: "testProperty",
room: this.props.room
});
this.props.socket.on("test", response => {
alert("response received: " + response.key);
});
};
render() {
<View>
<TouchableOpacity
onPress={this.onTest}
/>
</View>
}
}
我希望在连接的两个客户端上都读取服务器消息,房间中的每个客户端都会发送原始事件,但是只有发起客户端会收到服务器消息,第二个客户端不在同一房间中
答案 0 :(得分:0)
我认为您需要在server.js中
socket.join(test.room);