Vue Socket.io:客户端未从服务器接收消息

时间:2019-03-18 05:38:08

标签: javascript node.js vue.js websocket socket.io

我正在使用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));
    }
  }
}

我能够从客户端向服务器发出“联合游戏”,但好像没有从服务器向客户端发出“开始游戏”

2 个答案:

答案 0 :(得分:0)

您已在函数内部安装了函数。尝试把它放在外面。

https://vuejs.org/v2/api/#mounted

答案 1 :(得分:0)

如果任何人遇到客户未收到排放物的问题, 我的问题是:

我已经在套接字中添加了套接字,如下所示:

    connect() {
      this.isConnected = true;
      console.log("socket hit");
    }
  },

由于某种原因,此方法不起作用(请参考一些教程并找到了它)。

在“ mount()”中,我什么都没有。我现在添加了:

    this.socket.on('connect', () => {
      console.log("emit received from server");
    });
  },

这很好,我可以看到发射了。