ProductPromotion
Logo

0x3d.Site

is designed for aggregating information.

Building the Server

In this module, you will focus on building the server for your real-time chat application. This involves setting up the Express server, integrating Socket.io, and handling user connections and messages. By the end, you will have a functioning server capable of managing real-time communication between clients.

Setting Up the Express Server

Step 1: Creating the Server File

Open the index.js file located in the src folder. This file will serve as the main entry point for your server. You will write code to create an Express application and set up an HTTP server.

  1. Import Required Modules: Start by importing the necessary modules at the beginning of the file:

    const express = require('express');
    const http = require('http');
    const socketIo = require('socket.io');
    
  2. Initialize Express and HTTP Server: Create an instance of Express and set up an HTTP server:

    const app = express();
    const server = http.createServer(app);
    const io = socketIo(server);
    
  3. Define the Port: Specify the port on which the server will listen. Use an environment variable for flexibility, with a default of 3000:

    const PORT = process.env.PORT || 3000;
    

Step 2: Serving Static Files

To serve your HTML and CSS files, use Express's built-in middleware to serve static files from the public directory.

  1. Add Static Middleware: Insert the following line to serve static assets:

    app.use(express.static('public'));
    

Step 3: Starting the Server

Next, you will need to start the server and listen for incoming connections. Add the following code:

server.listen(PORT, () => {
   console.log(`Server is running on http://localhost:${PORT}`);
});

At this point, you have a basic Express server set up, ready to handle incoming requests.

Integrating Socket.io

Step 1: Setting Up Socket.io

Socket.io makes it possible to manage real-time communication easily. You will integrate it with your existing server.

  1. Configure Socket.io: After initializing io with your HTTP server, you can define connection events to handle incoming connections from clients. Add the following code just after setting up the server:

    io.on('connection', (socket) => {
        console.log('A user connected');
    
        // Handle disconnection
        socket.on('disconnect', () => {
            console.log('A user disconnected');
        });
    });
    

Step 2: Listening for Messages

To enable chat functionality, you need to listen for messages sent by users and broadcast them to all connected clients.

  1. Create an Event for Incoming Messages: Inside the connection callback, add an event listener for messages:

    socket.on('chat message', (msg) => {
        console.log(`Message received: ${msg}`);
        io.emit('chat message', msg); // Broadcast the message to all clients
    });
    

This code listens for a chat message event, logs the message to the console, and then emits it to all connected clients.

Handling User Names

To make the chat more engaging, you can allow users to set their names. This involves managing user data and broadcasting messages accordingly.

Step 1: Storing User Names

You can store user names in a simple object or map. Create a new object to track connected users:

const users = {};

Step 2: Managing User Connections

Update your connection event to handle user names. When a user connects, you can prompt them for their name.

  1. Prompt for User Name: Modify the connection event to ask for a name:

    socket.on('set name', (name) => {
        users[socket.id] = name; // Store the user's name using their socket ID
        socket.emit('name set', name); // Confirm the name has been set
        console.log(`${name} has joined the chat`);
    });
    

Step 3: Sending Messages with User Names

When broadcasting messages, include the user name along with the message text. Update the chat message event handler:

socket.on('chat message', (msg) => {
   const name = users[socket.id] || 'Anonymous'; // Fallback to 'Anonymous' if no name is set
   const message = `${name}: ${msg}`;
   console.log(`Message received: ${message}`);
   io.emit('chat message', message);
});

Testing the Server

After implementing the server logic, you should test it to ensure everything works correctly.

Step 1: Starting the Server

Make sure your server is running. Use the following command:

node src/index.js

Step 2: Opening the Chat App

Navigate to http://localhost:3000 in your web browser. Open multiple tabs to simulate multiple users.

Step 3: Testing User Connections

  1. Set User Names: In your client-side script (which you will create shortly), emit the set name event to assign names to users.

  2. Send Messages: Use the input field to send messages. Confirm that messages are displayed with user names in all open tabs.

Creating a Basic Client-Side Script

To handle the interaction between the server and clients, you will need to create a client-side JavaScript file.

Step 1: Creating the Client-Side Script

Inside the public folder, create a file named script.js. This file will manage socket connections and user interactions.

Step 2: Setting Up the Socket Connection

At the top of your script.js file, establish a connection to the Socket.io server:

const socket = io();

Step 3: Handling User Input

You will need to capture user input and emit events to the server. Add the following code:

const sendButton = document.getElementById('send-button');
const messageInput = document.getElementById('message-input');

sendButton.addEventListener('click', () => {
   const msg = messageInput.value;
   socket.emit('chat message', msg);
   messageInput.value = ''; // Clear the input field
});

Step 4: Receiving Messages

To display incoming messages, listen for the chat message event and append messages to the chat window:

const messagesContainer = document.getElementById('messages');

socket.on('chat message', (msg) => {
   const messageElement = document.createElement('div');
   messageElement.textContent = msg;
   messagesContainer.appendChild(messageElement);
});

Step 5: Setting User Name

Prompt the user for their name and emit the set name event upon loading the page:

const userName = prompt('What is your name?');
socket.emit('set name', userName);

Conclusion

In this module, you built the server for your real-time chat application using Express and Socket.io. You established a basic server structure, integrated real-time communication, and managed user connections and messages. With the server now set up, you are ready to enhance the functionality further in the upcoming modules. This foundational work is essential for creating a responsive and engaging chat experience.

Real-time Chat App with Node.js and Socket.io

This course guides you through creating a real-time chat application using Node.js and Socket.io. You'll learn about setting up the server, managing WebSocket connections, and implementing front-end functionality.
  1. Collections 😎
  2. Frequently Asked Question's 🤯
  3. Shortcuts 🥱
  4. Error Solutions 🤬

Tools

available to use.

Providers

to have an visit.

Made with ❤️

to provide resources in various ares.
  1. Home
  2. About us
  3. Contact us
  4. Privacy Policy
  5. Terms and Conditions

Resouces

to browse on more.
0x3d
https://www.0x3d.site/
0x3d is designed for aggregating information.
NodeJS
https://nodejs.0x3d.site/
NodeJS Online Directory
Cross Platform
https://cross-platform.0x3d.site/
Cross Platform Online Directory
Open Source
https://open-source.0x3d.site/
Open Source Online Directory
Analytics
https://analytics.0x3d.site/
Analytics Online Directory
JavaScript
https://javascript.0x3d.site/
JavaScript Online Directory
GoLang
https://golang.0x3d.site/
GoLang Online Directory
Python
https://python.0x3d.site/
Python Online Directory
Swift
https://swift.0x3d.site/
Swift Online Directory
Rust
https://rust.0x3d.site/
Rust Online Directory
Scala
https://scala.0x3d.site/
Scala Online Directory
Ruby
https://ruby.0x3d.site/
Ruby Online Directory
Clojure
https://clojure.0x3d.site/
Clojure Online Directory
Elixir
https://elixir.0x3d.site/
Elixir Online Directory
Elm
https://elm.0x3d.site/
Elm Online Directory
Lua
https://lua.0x3d.site/
Lua Online Directory
C Programming
https://c-programming.0x3d.site/
C Programming Online Directory
C++ Programming
https://cpp-programming.0x3d.site/
C++ Programming Online Directory
R Programming
https://r-programming.0x3d.site/
R Programming Online Directory
Perl
https://perl.0x3d.site/
Perl Online Directory
Java
https://java.0x3d.site/
Java Online Directory
Kotlin
https://kotlin.0x3d.site/
Kotlin Online Directory
PHP
https://php.0x3d.site/
PHP Online Directory
React JS
https://react.0x3d.site/
React JS Online Directory
Angular
https://angular.0x3d.site/
Angular JS Online Directory