Aquarius_Girl
Aquarius_Girl

Reputation: 22906

socket.on inside socket.on server side api socket.io in nodejs

Why do we require to put socket.on inside socket.on here? What does this represent? Is there any other way of writing this?

This is the code of server.js in nodejs.

var objExpress = require('express')()
var objHttp = require('http').createServer(objExpress)
var objSocketIO = require('socket.io')(objHttp)

objExpress.get('/', (request, result) => result.send('hello'))

objSocketIO.on('connection', (argSocket) => {
  console.log('A user connected!');
  argSocket.on('message', (argMsg) => {
    console.log(argMsg);
    argSocket.broadcast.emit('message-broadcast-xyz', argMsg)
  })
})

objHttp.listen(3000, () => {
  console.log("Listening on port 3000")
})

Upvotes: 0

Views: 80

Answers (1)

jfriend00
jfriend00

Reputation: 707158

Inside of this:

objSocketIO.on('connection', argSocket => {
    // here's where you know the socket for a newly connected socket
});

is the only place where you get notified of a newly connected socket. If you want to listen for events on that newly connected socket, then this is the place to install those event listeners.

objSocketIO.on('connection', argSocket => {
    // here's where you know the socket for a newly connected socket
    // and where you can install event listeners on that newly connected socket
    argSocket.on('message', (argMsg) => {
        // here's where you get a message on that connected socket
        // from the previously installed event handler
        argSocket.broadcast.emit('message-broadcast-xyz', argMsg)
    });
});

Why do we require to put socket.on inside socket.on here?

Well, that's how event driven programming works. You listen for an event by installing an eventListener. In this case, when you get an event from your server that a new socket has connected, then you install event listeners on that new socket so you can get events from it.

Is there any other way of writing this?

Other ways could be dreamed up, but they'd have to be doing something like this under the covers because listening for events is the way you program with servers and sockets in node.js.

Upvotes: 1

Related Questions