Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 18, 2023 12:33 pm GMT

Creating a Real-Time Chat Application with Node.js and Socket.IO

Real-time chat applications have become quite popular in recent years, with the rise of platforms like Slack and Discord. I create a simple real-time chat application using Node.js and Socket.IO.

firstly, make sure you have Node.js installed on your system. You can download it from the official Node.js website.

Step 1: Initialize the Project
create a new directory for our project and initialize a new Node.js project in that directory. Open your terminal and run the following commands:

mkdir chat-appcd chat-appnpm init -y

it will create a new directory called chat-app and initialize a new Node.js project in that directory.

Step 2: Installation of Dependencies
I installed the dependencies or package i need for our project "chatapp".
Run the following command:

npm install express socket.io mongoose body-parser

express: A popular Node.js web framework for building web applications.
socket.io: A library for building real-time applications using Web Sockets.
mongoose: A popular MongoDB library for Node.js.
body-parser: A middleware for parsing request bodies.

Step 3: Set up the Server
I set up an Express server and handle the incoming request. Create a new file called index.js in the root of your project directory and add the following code:

const express = require('express');const app = express();const http = require('http').createServer(app);const io = require('socket.io')(http);// Serve static files from the public directoryapp.use(express.static('public'));// Listen for incoming connectionsconst port = process.env.PORT || 7654;http.listen(port, () => {  console.log(`Server running at http://localhost:${port}`);});

Step 4: Set up the Client
I create the client-side HTML, CSS, and JavaScript files. Create a new directory called public in the root of your project directory. Inside the public directory, create a new file called index.html and add the following code:

<!DOCTYPE html><html><head>  <title>Chat App</title>  <link rel="stylesheet" href="style.css"></head><body>  <div id="messages"></div>  <form id="message-form">    <input type="text" name="name" placeholder="Name">    <input type="text" name="message" placeholder="Message">    <button>Send</button>  </form>  <script src="/socket.io/socket.io.js"></script>  <script src="chat.js"></script></body></html>

Original Link: https://dev.to/famakinwaris/creating-a-real-time-chat-application-with-nodejs-and-socketio-3035

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To