Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
unable to connect to nodejs server from react client with SocketIO

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda