-1

Can anyone help me to figure out this code .I'm new to Socket.io I just wanted to see how actually client and server interacts. Code in Express.js is here :

const express = require('express');
const router = express.Router();
const io = require('socket.io')();
const iio = require('socket.io-client');

const po = iio("http://localhost:5000");
po.connect();
const nsp = io.of("http://localhost:5000");

router.get ('/',async (req,res)=> {
    try {
        nsp.emit('connec', {message:"response from  socket"})
        
        
        po.on('connec', (message) => {
          console.log("socket"+message);
        })
        
        res.send({message:"its get request"});
    } catch(error) {
        console.error(error.message);
        res.status(500).send("INTERNAL SERVER ERROR");
    }
})

module.exports = router;

thanks in advance.

I tried to make a web-socket using Socket.io but it is not listening events properly .

1 Answers1

0

Brother there are 3 things:-

  1. Socket.io requires 2 setups: server-side setup and client-side setup. You only provided the code of the server-side setup for your MERN app.
  2. Socket.io's server-side setup is done in the server file. In the code you have shared above, you are not doing it in server file. You are doing this setup in a route file, which is not correct.
  3. Socket.io's client-side setup is done in the front-end you are using like ReactJS/template engine like EJS/plain HTML file. In your code above, you have incorrectly added the client-side setup in the route file. socket.io-client library is to be added in the front-end, not in the back-end/server.

You can follow this guide on Socket.io's official website to understand it. It is very beginner-friendly: https://socket.io/get-started/chat

MBS
  • 72
  • 7