在node.js上的socket.io上发送消息client-> server->客户端 [英] Sending messages client->server->client on socket.io on node.js

查看:88
本文介绍了在node.js上的socket.io上发送消息client-> server->客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的 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);

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

The reason I know it works is because, when I load the page and this script executes:

// 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)类似新玩家! weka连接在坐标上的地图4上(10,5)

I get in my dialogbox ("CSS div") something like New player! weka connected on map 4 on coordinates (10,5)

好的,很酷,所以它有效!但是,当我移动时,我尝试使用此

OK, cool, so it works! However, when I "move" I try sending a message to server using this

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

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

I don't even see console say Testing. I don't know why.

推荐答案

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

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

服务器端。当有人移动时,会发出'updatePlayer'对于除原始播放器之外的每个插槽。在每个客户端,拦截updatePlayer。

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

这篇关于在node.js上的socket.io上发送消息client-> server->客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆