<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Nivedin</title>
    <description>The latest articles on Forem by Nivedin (@nivedin).</description>
    <link>https://forem.com/nivedin</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F692754%2F460c636a-c57b-42a1-a5d5-2673985653e7.jpg</url>
      <title>Forem: Nivedin</title>
      <link>https://forem.com/nivedin</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/nivedin"/>
    <language>en</language>
    <item>
      <title>Real time chat using Socket.io</title>
      <dc:creator>Nivedin</dc:creator>
      <pubDate>Tue, 07 Sep 2021 18:30:33 +0000</pubDate>
      <link>https://forem.com/nivedin/real-time-chat-using-socket-io-134l</link>
      <guid>https://forem.com/nivedin/real-time-chat-using-socket-io-134l</guid>
      <description>&lt;h1&gt;What are WebSockets?&lt;/h1&gt;

&lt;p&gt;Socket.IO enables real-time, bidirectional and event-based communication.&lt;br&gt;
It works on every platform, browser or device, focusing equally on reliability and speed.&lt;/p&gt;

&lt;p&gt;Socket.IO allows you to bridge the gap between clients and servers, or any other kind of device. It works on every platform, browser or device, focusing equally on reliability and speed. Learn how easy it is to integrate socket functionality into your web app in under ten minutes!&lt;/p&gt;

&lt;p&gt;Now let us see how to use Socket.io&lt;/p&gt;

&lt;p&gt;The tools that we are going to use are,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Nodejs and Express&lt;/li&gt;
&lt;li&gt;Reactjs&lt;/li&gt;
&lt;li&gt;and obviously Socket.io 😂 &lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Let us start &lt;/h2&gt;

&lt;p&gt;We will be building a simple chat app using Nodejs and React.&lt;/p&gt;

&lt;p&gt;First initialize our server&lt;br&gt;
&lt;code&gt;npm init&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Then install the dependencies&lt;br&gt;
&lt;code&gt;npm install express socket.io&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Run the server&lt;br&gt;
&lt;code&gt;node server.js&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Let start coding our server now,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const socket = require("socket.io");

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

// Static files
app.use(express.static("public"));

// Socket setup
const io = socket(server);

io.on("connection", function (socket) {
  console.log("Made socket connection");
  const { roomId } = socket.handshake.query;
  socket.join(roomId);

  // Listen for new messages
  socket.on(NEW_CHAT_MESSAGE_EVENT, (data) =&amp;gt; {
    io.in(roomId).emit(NEW_CHAT_MESSAGE_EVENT, data);
  });

  // Leave the room if the user closes the socket
  socket.on("disconnect", () =&amp;gt; {
    socket.leave(roomId);
  });
});
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the socket is open, it listens for the event we emit in the React app. The message, that is carried by that event, is then forwarded to all users in the same room by emitting another event. The client picks up the event and adds the message to the array of all messages.&lt;/p&gt;

&lt;p&gt;Let us create the front-end now using Reactjs,&lt;/p&gt;

&lt;p&gt;Set up the react evironment using create-react-app&lt;br&gt;
&lt;code&gt;npx create-react-app socketio-chat&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Install the dependencies&lt;br&gt;
&lt;code&gt;npm install socket.io-client react-router-dom&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Start the app,&lt;br&gt;
&lt;code&gt;npm start&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;We will be creating two pages&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Home page - To enter roomId&lt;/li&gt;
&lt;li&gt;Chat Page - To chat&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;App.js&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

import "./app.css";
import Home from "./pages/Home";
import ChatRoom from "./page/ChatRoom";

function App() {
  return (
    &amp;lt;Router&amp;gt;
      &amp;lt;Switch&amp;gt;
        &amp;lt;Route exact path="/" component={Home} /&amp;gt;
        &amp;lt;Route exact path="/:roomId" component={ChatRoom} /&amp;gt;
      &amp;lt;/Switch&amp;gt;
    &amp;lt;/Router&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;Home.js&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React,{useState} from "react";
import { Link } from "react-router-dom";


const Home = () =&amp;gt; {
  const [roomName, setRoomName] = useState("");

  const handleRoomNameChange = (event) =&amp;gt; {
    setRoomName(event.target.value);
  };

  return (
    &amp;lt;div className="home-container"&amp;gt;
      &amp;lt;input
        type="text"
        placeholder="Room"
        value={roomName}
        onChange={handleRoomNameChange}
        className="text-input-field"
      /&amp;gt;
      &amp;lt;Link to={`/${roomName}`} className="enter-room-button"&amp;gt;
        Join room
      &amp;lt;/Link&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Home;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;Chat Room &lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

import useChatMessage from "../hooks/useChatMessage";

const ChatRoom = (props) =&amp;gt; {
  const { roomId } = props.match.params; // Gets roomId from URL
  const { messages, sendMessage } = useChatMessage(roomId); // Creates a websocket and manages messaging
  const [newMessage, setNewMessage] = React.useState(""); // Message to be sent

  const handleNewMessageChange = (event) =&amp;gt; {
    setNewMessage(event.target.value);
  };

  const handleSendMessage = () =&amp;gt; {
    sendMessage(newMessage);
    setNewMessage("");
  };

  return (
    &amp;lt;div className="chat-room-container"&amp;gt;
      &amp;lt;h1 className="room-name"&amp;gt;Room: {roomId}&amp;lt;/h1&amp;gt;
      &amp;lt;div className="messages-container"&amp;gt;
        &amp;lt;ol className="messages-list"&amp;gt;
          {messages.map((message, i) =&amp;gt; (
            &amp;lt;li
              key={i}
              className={`message-item ${
                message.ownedByCurrentUser ? "my-message" : "received-message"
              }`}
            &amp;gt;
              {message.body}
            &amp;lt;/li&amp;gt;
          ))}
        &amp;lt;/ol&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;textarea
        value={newMessage}
        onChange={handleNewMessageChange}
        placeholder="Write message..."
        className="new-message-input-field"
      /&amp;gt;
      &amp;lt;button onClick={handleSendMessage} className="send-message-button"&amp;gt;
        Send
      &amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default ChatRoom;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let us create a hook to manage the socket and incomming-outgoing messages,&lt;/p&gt;

&lt;h2&gt;useChatMessage.js&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect, useRef, useState } from "react";
import socketIOClient from "socket.io-client";

const NEW_CHAT_MESSAGE_EVENT = "newChatMessage"; // Name of the event
const SOCKET_SERVER_URL = "http://localhost:5000";

const useChatMessage= (roomId) =&amp;gt; {
  const [messages, setMessages] = useState([]); // Sent and received messages
  const socketRef = useRef();

  useEffect(() =&amp;gt; {

    // Creates a WebSocket connection
    socketRef.current = socketIOClient(SOCKET_SERVER_URL, {
      query: { roomId },
    });

    // Listens for incoming messages
    socketRef.current.on(NEW_CHAT_MESSAGE_EVENT, (message) =&amp;gt; {
      const incomingMessage = {
        ...message,
        ownedByCurrentUser: message.senderId === socketRef.current.id,
      };
      setMessages((messages) =&amp;gt; [...messages, incomingMessage]);
    });

    // Destroys the socket reference
    // when the connection is closed
    return () =&amp;gt; {
      socketRef.current.disconnect();
    };
  }, [roomId]);

  // Sends a message to the server that
  // forwards it to all users in the same room
  const sendMessage = (messageBody) =&amp;gt; {
    socketRef.current.emit(NEW_CHAT_MESSAGE_EVENT, {
      body: messageBody,
      senderId: socketRef.current.id,
    });
  };

  return { messages, sendMessage };
};

export default useChatMessage;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's its friends we have created our real-time-chat-app using node-react.&lt;br&gt;
P.S I have skipped the CSS, you guys can add the color to it 😁&lt;/p&gt;

&lt;p&gt;For more information you can visit socket.io official web page &lt;a href="https://socket.io"&gt;Socket.io&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>node</category>
      <category>socket</category>
      <category>realtime</category>
    </item>
  </channel>
</rss>
