gpt4 book ai didi

javascript - Socket.io 发送到特定客户端

转载 作者:太空宇宙 更新时间:2023-11-04 02:58:24 25 4
gpt4 key购买 nike

有人能告诉我为什么我会收到未定义的响应吗?

正如我所检查的,它肯定保存了 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);

客户端.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(){});
});

最佳答案

这只是因为您登录错误。

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

关于javascript - Socket.io 发送到特定客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23974954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com