Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 访问socket.io中socket.on(';连接';)内的其他套接字_Javascript_Node.js_Socket.io - Fatal编程技术网

Javascript 访问socket.io中socket.on(';连接';)内的其他套接字

Javascript 访问socket.io中socket.on(';连接';)内的其他套接字,javascript,node.js,socket.io,Javascript,Node.js,Socket.io,我是node.js和socket.io的新手 如何访问socket.on('connection')中的其他套接字? 这是我的服务器端代码: 服务器端index.js: 感谢您的帮助。如果您希望某些数据(如头像)在收到后可用于将来的活动,那么您必须将该数据保存在服务器中的某个位置,并以您知道哪些数据与哪个连接相关联的方式保存 有无数种方法可以构造它,从将其保存到套接字上的属性,到将其保存为用户名-->用户数据的映射,再到将其保存到数据库中。一般的想法是,当您收到数据时,将其保存在某个位置,以便无

我是node.js和socket.io的新手

如何访问socket.on('connection')中的其他套接字? 这是我的服务器端代码:

服务器端index.js:

感谢您的帮助。

如果您希望某些数据(如头像)在收到后可用于将来的活动,那么您必须将该数据保存在服务器中的某个位置,并以您知道哪些数据与哪个连接相关联的方式保存

有无数种方法可以构造它,从将其保存到套接字上的属性,到将其保存为用户名-->用户数据的映射,再到将其保存到数据库中。一般的想法是,当您收到数据时,将其保存在某个位置,以便无论您将来如何检索数据以用于某些未来事件,都可以在该数据结构或数据库中找到它

根据您的代码示例:

io.sockets.on("connection", function (socket) {

    var savedFruit;
    socket.on("tree", function(fruit){
        savedFruit = fruit;
        console.log(fruit); // result: strawberry
    });

    socket.on("drink", function(juice){
        // You can access the savedFruit variable here which will only have a
        // value if the "tree" message has already been received.
    });

});

你好,jfriend00,是的,我已经在使用这个数据库了。这只是示例代码。主要的问题仍然是“如何访问socket.io中的socket.on('connection')”中的其他套接字”干杯…@Kiky-其他套接字是什么意思?还有什么插座?您的示例代码询问如何访问化身,而不是如何访问另一个套接字。jfriend00,Ok。。这不是关于阿凡达。我更新我的问题。希望你现在明白了。很抱歉因为我对javascript和socket.io非常熟悉。谢谢。@Kiky-水果的答案还是一样的。将该值保存在其他事件处理程序可以访问的位置。在您的特定情况下,您可以重命名
fruit
变量,使其与函数参数不冲突,并将声明向上移动一个作用域级别,使其高于现在声明的位置,以便对两个事件处理程序都可用。jfriend00。。。嗯。。你能用你的示例代码回答吗?谢谢你指导我。。。
io.sockets.on("connection", function (socket) {

    var savedFruit;
    socket.on("tree", function(fruit){
        savedFruit = fruit;
        console.log(fruit); // result: strawberry
    });

    socket.on("drink", function(juice){
        // You can access the savedFruit variable here which will only have a
        // value if the "tree" message has already been received.
    });

});