0

I'm using react frontend with express backend.

React socket code

import io from "socket.io-client";

function ReactComponent() {
    const socket = io("http://localhost:5000");

    socket.on('connection', () => {
        console.log("connection")
    });

    useEffect(() => {
        socket.emit('new-user', "hello");
    }, []);

    return(<p>Test text</p>);
}
    
export default ReactComponent;

Express socket code

const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);

io.on('connection', (socket) => {
    console.log("New client connected");

    socket.on('new-user', (room) => {
        socket.join(room);
        socket.to(room).broadcast.emit('user-connected', "thx for info");
    })
});

From looking at the documentation and other examples, this should work and if it does, express should print out "New client connected" yet that doesn't happen.

Edward
  • 335
  • 1
  • 3
  • 9

3 Answers3

1

Took a while to find this. Hope this helps someone else in the future!

On the express I used to have:

const http = require('http').Server(app);
const io = require('socket.io')(http);

const port = process.env.PORT || 5000;
app.listen(port);

Instead, it should have been:

const port = process.env.PORT || 5000;
var server = app.listen(port);

var io = require('socket.io')().listen(server);

Notice how there is no mention of the http module as most of the other answers require it.

A helpful thread to help understand the problem is here: Express.js - app.listen vs server.listen

Additionally, the docs for this are here: https://socket.io/docs/v4/server-initialization/

Edward
  • 335
  • 1
  • 3
  • 9
0

You are not emitting to the listener called connection at your backend. You have to communicate to the listener at the backend

import io from "socket.io-client";

function ReactComponent() {
    const socket = io("http://localhost:5000");

    socket.emit('connection');
   
}

Udendu Abasili
  • 1,163
  • 2
  • 13
  • 29
0

If you have used app.listen() in your code, then you need to change it to http.listen(), and then it should work.

Because the app has been already passed while creating the http server. It means that this http needs to listen on some port and not the app.

amrendra
  • 345
  • 2
  • 12