Socket.io可能的发射器问题

时间:2018-08-31 14:21:15

标签: javascript reactjs redux socket.io game-development

我最近开始进入socket.io。通过在带有Redux和TS的React上实现多人游戏来学习。

这是我在redux devtools中注意到的一个奇怪问题的视频。我不确定这是否是Redux或Socket.io的问题。您将看到的是一个间隔内触发的操作,该操作会更改players数组。该动作不会以任何方式影响player (注意单数)对象。

这是Socket.io的问题,还是您怀疑Redux devtools出了问题,还是菜鸟socket.io开发人员(我)做错了?

Redux devtools in two tabs

服务器

// server.js

const io = require('socket.io')();

/**
 * When a player joins
 */
const SUBSCRIBE_PLAYER = "subscribePlayer";
const DISCONNECT = "disconnect";
/**
 * Current players, etc
 */
const SERVER_STATE = "state";

/**
 * Initial state
 */
const players = {};
let playerScore = 0;

/**
 * Handle socket connections incomming from client
 */
io.on('connection', (socket) => {
  socket.on(SUBSCRIBE_PLAYER, (data) => {
    console.log("+++++++++++++")
    console.log(`ID: ${data.id}`)
    console.log(`NAME: ${data.name}`)
    console.log(`SCORE: ${data.score}`)
    console.log("+++++++++++++")

    /**
     * Check if unique player
     */
    players[data.id] = {
      id: data.id,
      name: data.name,
      score: data.score,
    }
  });

  socket.emit(SUBSCRIBE_PLAYER, { id: socket.id, name: "",  score: playerScore });

  /**
   * Remove player on disconnect
   */
  socket.on(DISCONNECT, (reason) => {   
    delete players[socket.id];
  });
});

/**
 * Notify client about server state
 */
setInterval(() => {
  io.sockets.emit(SERVER_STATE, players);
}, 1000);

const port = 8000;
io.listen(port);
console.log('Client listening on port ' + port);

客户

// This is being emitted in the above server.js in an interval
export function listenGameState(dispatch: Dispatch<any>) {
    socket.on(SERVER_STATE, (players: Players) => {
        // Plain action. Not a thunk
        dispatch(addPlayersAction(players)); // modifies only players object in the state
    });
}


// Reducer
export function commonReducer(state = initialState, action: ReducerActions) {
    switch (action.type) {
        case ADD_PLAYER: {
            return {
                ...state,
                player: {
                    id: action.payload.id,
                    name: action.payload.name,
                    score: action.payload.score,
                },
            };
        }
        case ADD_PLAYERS: {
            return {
                ...state,
                players: action.payload,
            };
        }
        default:
            return state;
    }
}

更新 最终没有对此做任何事情。似乎工作正常。但是,如果有人知道该问题,请随时发布答案。 :)

编码愉快!

0 个答案:

没有答案