【发布时间】:2018-07-02 00:26:44
【问题描述】:
目标
我正在寻找大量用户登录游戏室,例如game/#####。当用户点击该 url 时,他们的用户对象被创建并共享到该房间中的任何其他用户查看的状态。
问题
在componentDidMount 中,我调用我的Socket api 函数并传入userObj 和room 值。此信息会发送到 api 函数,然后也发送到服务器侦听器。但是,当服务器发出 join room 事件时,前端似乎没有听到它并通过使用新用户更新 state.game.users 对象来响应。
守则
server.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(8000);
io.on('connection', function (socket) {
socket.on('join room', (userObj, room) => {
socket.join(room).emit('join room', userObj);
});
socket.on('join chat', (msgObj, room) => {
socket.in(room).emit('join chat', msgObj);
});
socket.on('chat message', (msgObj, room) => {
socket.in(room).emit('chat message', msgObj);
});
});
api.js
import io from 'socket.io-client';
const socket = io.connect('http://localhost:8000');
export const joinRoom = (userObj, room) => {
socket.emit('join room', userObj, room);
}
export const joinChat = (msgObj, room) => {
socket.emit('join chat', msgObj, room);
}
export const chatMessage = (msgObj, room) => {
socket.emit('chat message', msgObj, room);
}
组件
import { joinRoom, joinChat, chatMessage } from './../../api';
class GameBoard extends Component {
constructor(props) {
super(props);
this.state = {
loading: true,
game: {
id: props.match.params.gameid,
users: {},
messages: []
}
};
this.socket = io('http://localhost:8000');
this.postUsername = this.postUsername.bind(this);
this.getBoardValues = this.getBoardValues.bind(this);
this.buildUserData = this.buildUserData.bind(this);
}
componentDidMount() {
this.socket.on('join room', (userObj) => {
this.postUser(userObj);
});
this.socket.on('join chat', (msgObj) => {
this.postMessage(msgObj);
});
this.socket.on('chat message', (msgObj) => {
this.postMessage(msgObj);
});
this.socket.on('connect', () => {
joinRoom(this.buildUserData(), this.state.game.id);
});
}
postUser(userObj) {
const game = this.state.game;
game.users[userObj.id] = userObj;
this.setState({ game });
}
...
【问题讨论】:
标签: javascript node.js reactjs socket.io