Socket.io发送给特定客户端

时间:2014-05-31 22:17:39

标签: javascript node.js socket.io

任何人都可以告诉我为什么我得到一个未定义的回应?

我肯定会保存socket.io套接字ID,正如我已经检查过的那样。响应的类型是“未定义”。它已成功连接,正如我在服务器代码(main.js)上看到的那样,我可以看到uuid以及套接字ID。

main.js

'use strict';
var uuid = require('node-uuid');
var fs = require('fs');
var fse = require('fs-extra');
var rimraf = require('rimraf');
var socketio = require('socket.io')();

var cnf = require('./config.js');

var myId = uuid.v4();
var connectedWorkers = {};

if (!fs.existsSync('runtime')) {
    console.log("runtime directory cannot be found");
}

rimraf.sync('runtime/generated');
fs.mkdirSync("runtime/generated", function(err){
    if(err){ 
        console.log(err);
        response.send("ERROR! Can't make the directory! \n");    // echo the result back
    }
});

socketio.on('connection', function(socket){
    console.log('connection!');
    var newId = uuid.v4();
    connectedWorkers[newId] = socket.id;
    socketio.sockets.in(connectedWorkers[newId]).emit("test", {asd:"asdasd"});
    console.dir(connectedWorkers);
});
socketio.listen(3000);

client.js

'use strict';

var cnf = require('./config.js');

var socket = require('socket.io-client')(cnf.serverURL);

socket.on('connect', function(data){
    console.log(data);
    socket.on('event', function(data){
    });
    socket.on('disconnect', function(){});
});

3 个答案:

答案 0 :(得分:3)

这只是因为你记错了。

socket.on('connect', function(data){    // this 'connect' event have no parameter. Just function()
    console.log(data);                  // therefore 'data' here will be 'undefined'
});

socket.on('test', function(data){
    console.log(data);                  // this will return {asd:"asdasd"} as you emitted this.
});

答案 1 :(得分:1)

您可以直接在套接字上调用emit

socketio.on('connection', function(socket){
    socket.emit("test", {asd:"asdasd"});
});

答案 2 :(得分:1)

您可以尝试在客户端侦听test事件:

'use strict';

var cnf = require('./config.js');

var socket = require('socket.io-client')(cnf.serverURL);

socket.on('test', function(data){
    console.log(data.asd);  //should print "asdasd"
});