DEV Community

AYOBAMI ABDULWARIS,FAMAKINWA
AYOBAMI ABDULWARIS,FAMAKINWA

Posted on

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-app
cd chat-app
npm init -y
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 directory
app.use(express.static('public'));

// Listen for incoming connections
const port = process.env.PORT || 7654;
http.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)