[英]How to receive data from server on two clients
I have a client-side test function, which sends a test object to a socket.io server whose job it is to wait for the client event, and then emit data to every client in the room that the original client emitted the event from. 我有一个客户端测试功能,该功能将测试对象发送到socket.io服务器,该服务器的工作是等待客户端事件,然后向原始客户端从中发出事件的房间中的每个客户端发送数据。 However, only the original client is receiving the event from the server. 但是,只有原始客户端正在从服务器接收事件。 the other client in the room is not receiving it. 房间中的其他客户端没有收到它。
I've tried both io.in(room).emit()
as well as io.to(room).emit()
server-side. 我已经尝试了io.in(room).emit()
和io.to(room).emit()
服务器端。 both clients definitely join the same room. 两个客户肯定会加入同一个房间。 and the server receives the event from the originating client, as well. 服务器也从原始客户端接收事件。
Server.js : 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);
});
Parent Component: 父组件:
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}
/>
);
}
}
Child Component: 子组件:
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>
}
}
I expect the server message to be read on both connected clients, every client in the room the original event was sent from, however only the originating client receives the server message, not the second client I the same room 我希望在连接的两个客户端上都读取服务器消息,房间中的每个客户端都会发送原始事件,但是只有原始客户端会收到服务器消息,而不是同一个房间中的第二个客户端
我认为在server.js中,您需要做
socket.join(test.room);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.