繁体   English   中英

Socket.io 1.x + Express(使用http):如何将消息发送到特定的客户端ID?

[英]Socket.io 1.x + Express (using http): How to send messages to specific client id?

我是socket.io的新手,并且正在使用NodeJS(表达4)做一个简单的API。 我正在开发类似于Facebook上的旧“戳”操作的操作。 一个用户向其他用户发送戳,并且该戳实时得到通知(这就是我使用socket.io的原因)。

这是代码:

app.js

var port   = 3000;
var app    = module.exports = express();
var server = require('http').Server(app);
...
server.listen(port);
require('./config/socket-io')(app, server, secret);

插座io.js

module.exports = function(app, server, secret) {
    var clients = {};
    console.log("initiating sockets...");
    var sio = require('socket.io').listen(server, {'log level': 2});

    sio.on('connection', function (socket) {
        console.log("...new connection: "+socket.client.id);
        clients[socket.id] = socket;
        socket.emit('identification', { data : socket.client.id });

        socket.on('newShoutOut', function(data) {
            var receptor    = data.idTo;
            var emiter      = socket.client.id;
            console.log("...new shout out from " +emiter+ " to "+receptor);
            sio.sockets.sockets[receptor].emit({ data : data.data, from : emiter });
        });

        socket.on('disconnect', function() {
            console.log("..."+socket.client.id + " disconnected");
        });
    });
};

在这里,您可以区分三种状态:

  • 连接:服务器检测到所有客户端与host:port的连接。 之后,服务器将其ID发送给每个客户端。 这很好。

  • 发送消息:一个客户端向另一个客户端发送通知。 目前,服务器从一个客户端接收通知,但是“接收者”什么也没有接收到。

  • 断开连接:在这种情况下无关紧要。

我的问题是,直接向该ID发送消息给客户端的方式是什么? 我做错了什么? 我尝试了很多选项,直接将消息发送到特定的客户端ID,但是没有用...

编辑

前端

var socket = io('http://localhost:3000');
var id = "";
socket.on('connection', function (data) {
    console.log("connected!");
    console.log(data);
});
socket.on('identification', function(data) {
    id = data.data;
    $("#socket_info h1").html("ID: "+id);
});
socket.on('newShoutOut', function(data) {
    console.log("newShoutOut received!");
});

好吧,所以我假设喊声来自用户? 您将需要在客户端上创建事件,例如:

var button = $('#button');

button.on('click', function() {
    var msg = 'message',
        userID = '123'; //get the ID who they are messaging

    socket.emit('sendShoutOut', {msg: msg, id: userID});
});

然后,您将需要在服务器上接收该响应,并使用该函数回复用户:

socket.on('sendShoutOut', function( data ) {

    socket.sockets.sockets[data.id].emit('sendPrivateMsg', { data : data.msg, from : emiter });
});

最后,必须通知接收方,因此您需要在客户端上处理响应:

socket.on('sendPrivateMsg', function( data ) { 
    alert(data);    
});

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM