Sim Kieu
Sim Kieu

Reputation: 41

Emit socket io event from React app and doesn't receive it at Node js server

I am trying to use Socket IO in my react app and for some reason, I can't get any event at my Node server from my React client. I can receive event at my React app emitted from the Node server, though.

My Node server looks like this:

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

const app = express();
const httpServer = http.createServer(app);
const io = socketio(httpServer, {
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"],
  }
});
const port = 4000;

io.on('connect', (socket) => {
  console.log('socket io connected');
  io.emit('message', 'a dog');
  io.emit('baby', 'a cat');
  io.on('baby', (msg) => {
    console.log(msg);
  });
  io.on('disconnect', (msg) => {
    console.log('io disconnected');
  });
});

httpServer.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`);
});

And my React app only has App.js and it looks like this:

import './App.css';
import socketClient from "socket.io-client";

const URL = "http://localhost:4000";
const socket = socketClient(URL);
socket.on('connect', () => {
  console.log(`I'm connected with the back-end`);
  socket.emit('baby', 'what is going on');
  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});
socket.on('message', (msg) => {
  console.log(msg);
});
socket.on('baby', (msg) => {
  console.log(msg);
});
socket.emit('baby', 'what is going on');

function App() {
  return (
    <div className="App">
    </div>
  );
}

export default App;

Like I mentioned above, I can only received socket events from my Node server and saw the messages printed out on my browser console but I don't see any message logs at my Node server. And even when I refresh my browser or turn off React app, it never prints 'io disconnected'. The only thing I saw at my Node server log is the message 'socket io connected'. Please help enlighten me, thank you very much!

Upvotes: 1

Views: 4582

Answers (1)

Fahad Farooq
Fahad Farooq

Reputation: 511

Change io.on('baby') and io.on('disconnect') on server to socket.on('baby') and socket.on('disconnect'). Basically, io.emit can be used to send a message to all connected sockets, but when you want to receive a message on the server, you listen for that message on individual sockets, otherwise you won't be able to distinguish between different clients connected to the server. Also note that when you want to send a message to just 1 client, you will again use socket.emit, not io.emit.

Upvotes: 3

Related Questions