0

I'm learning socketIO and I set up and running a basic nodejs server . My problem is that when I try to connect to the server with my nextJS app nothing happens. No errors occur and the messages I want to be printed on connection do not appear .

My code :

server.js in backend folder

const express = require('express');
const app = express();
const server = require('http').Server(app);
const { v4: uuidV4 } = require('uuid');
const cors = require('cors');

const io = require('socket.io')(server, {
  cors: true,
  origins:["http://localhost:3000"]
});

app.use(cors());
app.options('*', cors());

io.on('connection', socket => {
  socket.on('test',()=>{
   console.log(' i am a test') //does not appear 
  })
  
})

//I ALSO TRIED 
//io.on('test',()=>{
   //console.log('I am a test');
//})

server.listen(5000);

Then in my nextJS app in my frontend folder in index.js

import {useEffect} from 'react';
import io from 'socket.io-client';

const ENDPOINT = "http://localhost:5000";
const socket = io.connect(ENDPOINT);

  export default function Home() {

    useEffect(()=>{

     socket.emit('test');
    },[]);
    
   ...rest of code 
   
 }

So in my frontend app I emit the 'test' event to the server and the server did not console.log the response on connection

I would appreciate your help as I am new to socketIO

3
  • "http://localhost:3000" is not the same as -> "http://localhost:5000" You need to make sure ports are equal. Commented Nov 29, 2021 at 11:01
  • @Keith as I understand, the front-end is served on port 3000 (by a local dev server or something, like Angular-cli does on port 4200 with ng serve) and the back-end on port 5000 Commented Nov 29, 2021 at 11:02
  • @Keith my frontend is on port 3000 and my backend on 5000 Commented Nov 29, 2021 at 11:04

1 Answer 1

1

You can create a helper function in a separate file to manage the connections, listen to events and emit events. Here is one example for same :

export const socketConnection = io => {
  io.on("connection", socket => {
    console.log("Started socket connection!");

    socket.on("message", receivedMessage => {
      console.log("Socket message received", receivedMessage);
    });

    socket.on("subscribe", async room => {
      try {
        console.log(`In room`, socket.rooms);
        await socket.join(room);
        console.log(`[socket] Room Joined Successfully : ${room}`, room);
        await io.to(room).emit("subscribeSuccess", `Subscribed successfully ${socket.id}: room - ${socket.rooms}`);
      } catch (e) {
        console.log(`[socket] Error in Room Joining : ${room} : ${e}`, e);
        socket.emit("error", "couldnt perform requested action");
      }
    });

    socket.on("unsubscribe", async room => {
      try {
        await socket.leave(room);
        console.log(`[socket] Room Left Successfully : ${room}`, room);
      } catch (e) {
        console.log(`[socket] Error in Room Leaving : ${room} : ${e}`, e);
        socket.emit("error", "couldnt perform requested action");
      }
    });

  });
};

And then in app.js you can import and start a socket server.

import { socketConnection } from "@helpers";

const io = new Server(server, {
  transports: ["websocket", "polling"],
  allowEIO3: true
});
socketConnection(io);

And to connect to socket from client use this :

import io from 'socket.io-client';

const ENDPOINT = "http://localhost:5000";
const socket = io(ENDPOINT);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much . I will try this later . But what changes with this approach if you have a separate file?
It's just I think is a cleaner approach to maintain socket connection and listener rather than putting everything in app.js. Great that this helped you ! Thanks : )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.