简体   繁体   English

NodeJS中socket.io连接function中的“socket”有什么用?

[英]What is the usage of “socket” in socket.io connection function in NodeJS?

I am learning how to use socket.io in nodejs server.我正在学习如何在nodejs服务器中使用socket.io I see a example listed below and I would like to know what's the socket in connection function for?我看到下面列出的示例,我想知道连接 function 的socket是什么? Is it a new socket object?是新的插座object吗? And where's the 'id' from? 'id' 来自哪里? I have googled it but still not understand its function.我用谷歌搜索了它,但仍然不明白它的 function。 Thanks谢谢

Code:代码:

io.sockets.on('connection', function (socket) { //the socket in "function(socket)"
    socket.on('session_id', function (session_id) { socket.session_id = session_id; })
    setInterval(function() {
        socket.emit('date', {'date': new Date()});
    }, 1000);
}

Let's rework your example a little bit to remove a nested function.让我们稍微修改一下您的示例以删除嵌套的 function。

function connectionHandler (socket) { 
    socket.on('session_id', function (session_id) { 
        socket.session_id = session_id; 
    })
    setInterval(function() {
        socket.emit('date', {'date': new Date()});
    }, 1000);
 }

 io.sockets.on('connection', connectionHandler)

In your example, io.sockets is your socket.io server.在您的示例中, io.sockets是您的 socket.io 服务器。 io.sockets.on('connection', connectionHandler) registers a connection event handler function. io.sockets.on('connection', connectionHandler)注册一个连接事件处理程序 function。

Then, anytime a client (probably code running in a user's browser) connects, your connectionHandler gets called with the socket object for the current connection.然后,只要客户端(可能是在用户浏览器中运行的代码)连接,您的connectionHandler就会使用socket object 调用当前连接。

socket.on('session_id') sets up an event handler to listen for messages sent from clients with emit('session_id','some message payload') . socket.on('session_id')设置一个事件处理程序来监听从客户端发送的消息emit('session_id','some message payload')

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

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