How To Connect Socket In Node And Connect In React

Hello Friends, In this article, we will learn how to create a socket in Node and connect with react.

First, we need to create a server in the node.

npm init

After you run the command, it will add the package.json file to your project.

{
  "name": "socketchat",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}

Then, install npm and express socket.io command used for communication between web clients and servers.

npm install express socket.io

Then, add  below code in index.js file

const PORT = 5000;
const app = express();
const server = app.listen(PORT, function () {
  console.log(`Listening on port ${PORT}`);
  console.log(`http://localhost:${PORT}`);
});

// Socket setup
const io = socket(server, {
  cors: {
    origin: '*',
  }
});

io.on("connection", function (socket) {
  console.log("Made socket connection");
});

Then, add socket client-side for communication.

npm i socket.io-client

Then, connect socket at client side.

const socket = io('http://localhost:5000')

Then, start the socket server.

npm start

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories