Reputation: 23
I'm trying to develop a real-time quiz game using React and Socket IO. What I'm trying to achieve is when a player connects to a lobby other players should know it. Following is the code:
React
import React, { Component } from "react";
import { Modal, Button, Form } from 'react-bootstrap'
const socketIOClient = require("socket.io-client");
class PlayArea extends Component {
constructor() {
super();
this.state = {
playerList: [],
};
this.socket = socketIOClient('ip address');
this.socket.on('onPlayerJoin', data => {
this.setState({ playerList: data.playerList });
});
}
render() {
return (
Players Joined : <ul>{
this.state.playerList.map(player =>
(<li key={player.playerId}>{player.playerId}</li>)
)
}</ul>
);
}
}
Backend server:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
let playerId = 0;
let playerList = [];
let playerData = {
playerId: null,
}
io.on('connection', (socket) => {
console.log('A player has joined');
playerData.playerId = playerId;
playerId = playerId + 1;
playerList.push({ playerId: playerId });
socket.emit('onPlayerJoin', { playerList: playerList });
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
http.listen(3001, () => {
console.log('listening on *:3001');
});
The problem is when I open the page in a new browser instance(simulating a new player joining), the first instance is not receiving the "onPlayerJoin" event.
What am I doing wrong? Thanks for the help in advance.
Upvotes: 1
Views: 322
Reputation: 85
Replace
socket.emit('onPlayerJoin', { playerList: playerList });
with
socket.broadcast.emit('onPlayerJoin', { playerList: playerList });
This will send to all connected sockets except the sender while socket.emit only sends to that particular socket that got connected.
Upvotes: 2
Reputation: 176
The problem is in the backend. Using socket.emit()
,
you are sending the event only to the client that just connected.
You can use:
socket.broadcast.emit()
- send the event to all connected clients except the sender
io.emit()
- send the event to all connected clients.
Here is a cheatsheet: https://socket.io/docs/emit-cheatsheet/
Upvotes: 2