title: io.sockets.on not working inside a route in Node.js
body: <p>I'm trying to use io.sockets.on inside a route in a Node.js and Express app. I have been following what is said here: <a href="https://stackoverflow.com/a/31277123/8271839">https://stackoverflow.com/a/31277123/8271839</a></p>
  
  <p>I can successfully send io.sockets.emit events, but I cannot receive events with io.sockets.on.</p>
  
  <p>Here is my code:</p>
  
  <p>index.js:</p>
  
  <pre><code>const cors = require('cors');
  const express = require('express');
  const app = express();
  const server = require('http').Server(app);
  const io = require('socket.io')(server);
  const taskRequest = require('./routes/taskRequest');
  
  app.use(cors())
  app.use(express.json());
  app.use('/api/taskRequest', taskRequest);
  
  app.set('socketio', io);
  
  server.listen(4002);
  
  io.sockets.on("connection",function(socket){
      console.log("connected");
      socket.on("connected", function (data) {
          console.log("hello");
      })
  });
  </code></pre>
  
  <p>routes/taskRequest.js:</p>
  
  <pre><code>const express = require('express');
  const router = express.Router();
  
  router.post('/', async (req, res) =&gt; {
  
      var io = req.app.get('socketio');
  
      //pickedUser is one of the connected client
      var pickedUser = "JZLpeA4pBECwbc5IAAAA";
  
      //we only send the emit event to the pickedUser
      io.to(pickedUser).emit('taskRequest', req.body);
  
      io.on('connection', function (socket) {
          console.log('connected 2');
          socket.on('taskResponse', function () {
              console.log('hello 2');
          });
      });
  
  });
  
  module.exports = router; 
  </code></pre>
  
  <p>When a client is connected, I get the "connected" message in console, but not the "connected 2" message. </p>
  
  <p>Also, when client emits "connected" message, I get "hello" in console, but when clients emits "taskResponse" message, I don't get "hello 2" in console.</p>
  
  <p>Though when <code>io.to(pickedUser).emit('taskRequest', req.body);</code> is called, it works, client receives the "taskRequest" message.</p>
  
  <p>Why is .emit() working inside my route but not .on() ?</p>