简体   繁体   中英

React + SocketIO

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.

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM