Sending messages client->server->client on socket.io on node.js

后端 未结 2 1007
温柔的废话
温柔的废话 2020-12-30 10:29

I\'m using NodeJS+Socket.IO for simple web game. It works. Why?

Here\'s my server.js

var app = require(\'express\').createServer();
var          


        
相关标签:
2条回答
  • 2020-12-30 10:54

    Client-side. A player moves and the function movePlayer is executed:

    function movePlayer () {
        socket.emit ('player move', {map: 4, coords: '0.0'});
    }
    
    socket.on ('updatePlayer', function (msg) {
        console.log ('A player moves on map ' + msg.map + ' on coords ' + msg.coords);
    });
    

    Server-side. When someone moves, a 'updatePlayer' is emitted for each socket except the original player. On each client side, the updatePlayer is intercepted.

    socket.on ('player move', function (msg) {
        io.sockets.emit ('updatePlayer', msg);
    });
    
    0 讨论(0)
  • 2020-12-30 11:00

    Server side

    socket.on('updatePlayer', function(updatePlayer){
      console.log("Someone just moved on the map!")
      updatePlayer() // will trigger the client side function
    });
    

    Client side

    socket.emit('updatePlayer', function(){
      console.log('testing');
    })
    
    0 讨论(0)
提交回复
热议问题