Do you always have to wrap your socket.on in a io.on connection block?

Viewed 146

I am new to socket.io and have realized that every server-side eventlistenrs are wrapped in a io.on connection block:

io.on('connection', socket => {
  socket.on('event name', callback)
})

I am a little confused about two things:

  1. do I always have to wrap my socket.on in this kind of blocks? Is it because the socket represents the individual client that raised the connection event?
  2. Why should I use socket.on inside the block instead of io.on since they seem to do the same thing(like io.on('connection', () => io.on('event name', callback)))?
1 Answers

io.on() means adding an event listener to the server

io.on('connection', socket => {
  socket.on('event name', callback)
})

socket.on() means adding an event listener to the client as he connects

You cannot add an event listener to the client if he isn't connected, yet. So what we do, is we add an event listener to the server, that triggers, when a client connects. Once the client is connected, we add event listeners to him, that trigger, when he is sending data (for example)

Related