13

我正在使用 NodeJS+Socket.IO 进行简单的网页游戏。有用。为什么?

这是我的server.js

var app = require('express').createServer();
var io = require('socket.io').listen(app);

io.sockets.on('connection', function (socket) {
socket.on('set nickname' , function (nickname) {
socket.nickname = nickname;
console.log(nickname + ' just connected!');

});

socket.on('msg' , function (msg) {
socket.msg = msg;
io.sockets.emit('response', msg);
});

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

});

app.listen(8080);

我知道它有效的原因是,当我加载页面并且此脚本执行时:

// SERVER STUFF
socket.on('connect', function () {
    console.log('We are connected!');
    name = $(".name").val();
    this.emit('set nickname', name, function (success) {});
    msg = name + "|" + currX + "|" + currY + "|" + currentMap;
    this.emit('msg', msg, function (success) {});

    socket.on('response', function (data) {
        var theMsg = data.split("|");
        sayDialog("New player! " + theMsg[0] + " connected on map " + theMsg[3] + " on coordinates (" + theMsg[1] + "," + theMsg[2] + ")");
    });
});

我进入我的对话框(“CSS div”)类似于New player! weka connected on map 4 on coordinates (10,5)

好的,很酷,所以它有效!但是,当我“移动”时,我尝试使用它向服务器发送消息

  socket.on('updatePlayer', function () {
    console.log("Testing...");
  }); 

我什至没有看到console说测试。我不知道为什么。

4

2 回答 2

21

客户端。玩家移动并执行 movePlayer 函数:

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);
});

服务器端。当有人移动时,除了原始玩家之外,每个套接字都会发出一个“updatePlayer”。在每个客户端,updatePlayer 都会被拦截。

socket.on ('player move', function (msg) {
    io.sockets.emit ('updatePlayer', msg);
});
于 2012-05-15T12:43:47.717 回答
2

服务器端

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

客户端

socket.emit('updatePlayer', function(){
  console.log('testing');
})
于 2012-05-15T12:41:55.830 回答