0

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")
})
Adam Azad
  • 11,171
  • 5
  • 29
  • 70
Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Adam Azad Oct 08 '20 at 07:57
  • `objSocketIO` is the main instance of the library. When a new socket connection is detected, its `connection` event fires, and the *socket* instance is passed along; the inner event listener is attached to the *socket's* `message` event (in other words: false premise, you do not have socket.on inside socket.on) –  Oct 08 '20 at 07:58
  • @AdamAzad This question isn't a duplicate of that in any meaningful way I think –  Oct 08 '20 at 08:00

1 Answers1

1

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979