I am learning how to use socket.io
in nodejs
server. I see a example listed below and I would like to know what's the socket
in connection function for? Is it a new socket object? And where's the 'id' from? I have googled it but still not understand its 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 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.on('connection', connectionHandler)
registers a connection event handler 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.
socket.on('session_id')
sets up an event handler to listen for messages sent from clients with emit('session_id','some message payload')
.
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.