简体   繁体   English

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

[英]accessing other socket inside the socket.on('connection') in socket.io

I'm new with node.js and socket.io. 我是node.js和socket.io的新手。

How to access other socket inside socket.on('connection') ? 如何访问socket.on('connection')中的其他套接字? Here is my server side code: 这是我的服务器端代码:

server side index.js : 服务器端index.js

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

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

    socket.on("drink", function(juice){
        //How to access var fruit here? (strawberry)
    });

};

Thank you for any help.. 感谢您的任何帮助..

If you want some data (such as the avatar) to be available for future events after it is received, then you have to save that data somewhere in your server and save it in a way that you know which piece of data goes with which connection. 如果您希望某些数据(例如头像)在收到后可用于将来的事件,那么您必须将该数据保存在服务器中的某个位置,并以您知道哪个数据与哪个连接相关的方式保存。

There are a zillion ways to structure that from saving it to a property on the socket, to saving it a map of username --> userdata to saving it in a database. 从将它保存到套接字上的属性到保存用户名 - > userdata的映射以将其保存在数据库中,有很多方法可以构建它。 The general idea is that you save it somewhere when you receive it so that however you want to retrieve the data in the future for use in some future events, you can find it in that data structure or database. 一般的想法是,当您收到它时将其保存在某个地方,以便您将来要检索数据以便在将来的某些事件中使用,您可以在该数据结构或数据库中找到它。

From your code example: 从您的代码示例:

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

});

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

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