could anybody tell me why I'm getting an undefined response?
It's definitely saving the socket.io socket ID, as I've checked. The typeof the response is "undefined". It's successfully connecting, as I can see it on the server code (main.js), and I can see the uuid as well as the socket 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(){});
});
It's simply because you're logging wrong.
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.
});
You can call emit
directly on your sockets :
socketio.on('connection', function(socket){
socket.emit("test", {asd:"asdasd"});
});
You can try to listen test
event on the client side:
'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"
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.