【发布时间】:2019-08-08 10:51:19
【问题描述】:
我正在使用 Vue 和 Socket.io 构建多人游戏。我能够将数据从客户端发送到服务器,但反过来却不行,我不知道为什么。
这是我的一些代码:
app.js
var app = express();
app.use(cors());
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(4000);
// socket io
io.on('connection', function (socket) {
console.log('User connected ' + socket.id);
socket.on('disconnect', function(data) {
console.log('User disconnected ' + this.id);
});
socket.on('joined-game', function(data) {
console.log('player joined game' + this.id);
io.emit('start-game', { game: data });
});
});
在 JoinGame.vue
import axios from 'axios';
import * as io from 'socket.io-client';
export default {
data() {
return { games: "", invite: "", nickname: "", socket: io('http://localhost:4000') }
},
methods: {
joinGame() {
axios.get('http://localhost:5000/api/game/' + this.invite)
.then(response => {
this.games = response.data;
this.socket.emit('joined-game', { game: this.invite, nickname: this.nickname });
})
.catch(e => {
console.log(e);
});
}
}
}
在 AddPlayer.vue
中import axios from 'axios';
import * as io from 'socket.io-client';
export default {
data() {
return { invite: "", addedGame: false, waiting: true, socket: io('http://localhost:4000') }
},
methods: {
mounted() {
this.socket.on('start-game', function (data) {
console.log('player 2 joined game');
if(data.game === this.invite) {
this.waiting = false;
}
}.bind(this));
}
}
}
我能够从客户端向服务器发出“加入游戏”,但看起来“开始游戏”没有从服务器向客户端发出
【问题讨论】:
标签: javascript node.js vue.js websocket socket.io