How to create a chat application with Node.js and Socket.IO

6 lug 2023 2 min di lettura
How to create a chat application with Node.js and Socket.IO
Indice dei contenuti

Introduction

This tutorial will walk you through building a simple chat application using Node.js and Socket.IO.

Prerequisites

To follow this tutorial, you will need:

  1. Node.js and npm installed on your computer. You can download both from here.
  2. A code editor, such as Visual Studio Code.
  3. A basic understanding of JavaScript and HTML.

Installing dependencies

Open terminal or command prompt and navigate to the folder where you want to create your project. Once there, run the following command to initialize a new Node.js project:

npm init -y

Next, install express and socket.io using npm:

npm install express socket.io

Creating the server

Create a new file called server.js and insert the following code:

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

 const app = express();
 const server = http.createServer(app);
 const io = socketIo(server);

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

 io.on('connection', (socket) => {
 console.log('New client connected');

 socket.on('message', (message) => {
 io.emit('message', message);
 });

 socket.on('disconnect', () => {
 console.log('Client disconnected');
 });
 });

 server.listen(3000, () => {
 console.log('Listening on port 3000');
 });

This code initializes an express server and Socket.IO and configures the app to serve static files from the public folder. It also listens for socket connect and disconnect events and the message event to forward received messages to all connected clients.

Creating the client

Create a new folder called public and inside it, create a new file called index.html with the following code:

<!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Chat App</title>
 </head>
 <body>
 <ul id="messages"></ul>
 <form id="form">
 <input id="input" autocomplete="off" /><button>Send</button>
 </form>
 <script src="/socket.io/socket.io.js"></script>
 <script>
 const socket = io();
 const form = document.getElementById('form');
 const input = document.getElementById('input');

 form.addEventListener('submit', function(e) {
 e.preventDefault();
 if (input.value) {
 socket.emit('message', input.value);
 input.value = '';
 }
 });

 socket.on('message', function(message) {
 const item = document.createElement('li');
 item.textContent = message;
 document.getElementById('messages').appendChild(item);
 window.scrollTo(0, document.body.scrollHeight);
 });
 </script>
 </body>
 </html>

This HTML code contains a simple input form and a <ul> element for displaying messages. The JavaScript code handles the Socket.IO connection, sending messages to the server when the user submits the form, and adding new messages to the list when it receives a message from the server.

Application launch

You can now start the server with the following command:

node server.js

Open your browser and go to http://localhost:3000. You should see your simple chat application. You can open multiple browser tabs or windows to simulate multiple users and see how messages are broadcast to all clients.

Conclusion

Congratulations! You've just created a simple chat application using Node.js and Socket.IO. From here, you can add more features, like support for usernames, private chat rooms, direct messages, and more.

Buy me a coffeeBuy me a coffee

Supportaci se ti piacciono i nostri contenuti. Grazie.

Successivamente, completa il checkout per l'accesso completo a Noviello.it.
Bentornato! Accesso eseguito correttamente.
Ti sei abbonato con successo a Noviello.it.
Successo! Il tuo account è completamente attivato, ora hai accesso a tutti i contenuti.
Operazione riuscita. Le tue informazioni di fatturazione sono state aggiornate.
La tua fatturazione non è stata aggiornata.