Websocket Integration With Node

blog-banner

EveryOne building realTime apps with Socket.IO these days. Think a moment about it: There are a million other things that are built based on real-time applications. Do you want to build your own app with real-time updates? Let’s have a look at the basic configuration to build socket communication apps using Node and React Js.

List of things that we will learn from this blog

  • What is Socket programming
  • How to configure socket with Node and react js

Presumption: Before we proceed further, I assume that you have basic knowledge of NodeJs and reactJs

What is Socket programming

  • Socket is an internet communication protocol that provides bi-direction communication on top of TCP protocol
  • Using WebSocket, Client and Server can communicate with each other in a real-time manner.
  • Once the client is connected to the server, the client can receive data from the server without the need to continuously refresh the web page
  • Server can also receive data from client within the same connection

Configuration of socket with Node and React Js

  • Let’s create one directory with name Socket_connection_app
mkdir socket_connection_app && cd  Socket_connection_app
  • Initialize node project using below command, Which will create package.json file for you
    • npm init
  • We need to install express and socket.io package from node package manager
    • npm i express
    • npm i socket.io
  • Create app.js file on your project directory with will hold the actual server
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");

const port = 8080;
const route = require("./routes/index");

const app = express();
app.use(route);

const server = http.createServer(app);
const io = socketIo(server);
  • I hope you are aware with Node js and this code is not looking magic words to you
    • We can initialize Socket server by passing server object on defined variable socketIo
    • We also define an index route on our app. Even though we are not serving any HTML content to the client. It is necessary for a very simple route to listen for any incoming connection.
  • Now, create index.js file inside a routes directory :
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
res.send({ response: "I am alive" }).status(200);
});

module.exports = router;
  • I hope you are aware with Node js and this code is not looking a magic Designing socket
  • While configuring the socket server, the most important method we can see is on. It takes two-argument, first one is a type of event and the second one is event callback for every connection event
  • Connection event returns a socket object which will be passed to the callback function and by using this socket object server can send data back to the client.
let interval;

io.on("connection", (socket) => {
  console.log("New client connected");
  if (interval) {
    clearInterval(interval);
  }
  interval = setInterval(() => getApiAndEmit(socket), 1000);
  socket.on("disconnect", () => {
    console.log("Client disconnected");
    clearInterval(interval);
  });
});
  • Let’s improve getApiAndEmit method which will generate the message that can be send to the client
let interval;

io.on("connection", (socket) => {
  console.log("New client connected");
  if (interval) {
    clearInterval(interval);
  }
  interval = setInterval(() => getApiAndEmit(socket), 1000);
  socket.on("disconnect", () => {
    console.log("Client disconnected");
    clearInterval(interval);
  });
});

App.js File Example

const express = require("express");
const http = require("http");
const socketIo = require("socket.io");

const port = process.env.PORT || 4001;
const index = require("./routes/index");

const app = express();
app.use(index);

const server = http.createServer(app);

const io = socketIo(server);

let interval;

io.on("connection", (socket) => {
  console.log("New client connected");
  if (interval) {
    clearInterval(interval);
  }
  interval = setInterval(() => getApiAndEmit(socket), 1000);
  socket.on("disconnect", () => {
    console.log("Client disconnected");
    clearInterval(interval);
  });
});

const getApiAndEmit = socket => {
  const response = new Date();
  // Emitting a new message. Will be consumed by the client
  socket.emit("FromAPI", response);
};
server.listen(port, () => console.log(`Listening on port ${port}`));
  • To start the node server use below command for the same
    • To start the node server use below command for the same

Let’s implement the front end for second-hand communication(using react Js)

  • Create react js app
    • npx create-react-app socket_connection_app
  • Install socket client on your front end app
    • npm i socket.io-client
  • To make a simple structure, Let’s create an app.js file in the src directory
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://127.0.0.1:8080";

function App() {
  const [response, setResponse] = useState("");
  
  useEffect(() => {
    const socket = socketIOClient(ENDPOINT);
    socket.on("FromAPI", data => {
      setResponse(data);
    });
  }, []);
  
  return (
   <p>
    It's <time dateTime={response}>{response}</time>
   </p>
  );
}

export default App;
  • Start the react server and you can see the timestamp getting update every second by the magic of the socket
    • cd socket_connection_app
    • npm start
Contact us

For Your Business Requirements

Text to Identify Refresh CAPTCHA
Background Image Close Button

2 - 4 October 2024

Hall: 10, Booth: #B8 Brussels, Belgium