Creating a Chat using Socket.io and Javascript

Tiempo de lectura: 2 minutos

Reading time: 2 minutes

Hello, today I’m going to show you how to create a chat using Socket.io and JavaScript:

To get started, you’ll need to have Node.js and npm installed (https://nodejs.org/en/) on your computer. Then, follow these steps:

  1. Create a new directory for your project and open a command prompt in that directory.
  2. Run the command npm init to initialize your project. Follow the prompts to set up the name, version, and description of your project.
  3. Run the command npm install express socket.io to install the dependencies for your project. This will install Express, a server framework for Node.js, and Socket.io, a real-time communication library for JavaScript.
  4. Create a file called server.js and write the following code:
const express = require('express');
const socketio = require('socket.io');

const app = express();
const server = app.listen(3000, () => console.log('Listening on port 3000'));

const io = socketio(server);

io.on('connection', (socket) => {
  console.log('A user has connected');

  socket.on('disconnect', () => console.log('A user has disconnected'));
});

This code initializes a server using Express and then initializes Socket.io on the server. It then adds a connection and disconnection event to log a message in the console whenever a user connects or disconnects from the chat.

  1. Create a file called index.html and write the following code:
<!doctype html>
<html>
  <head>
    <title>Chat App</title>
  </head>
  <body>
    <div id="chat">
      <form id="send-message">
        <input type="text" placeholder="Type a message" />
        <button>Send</button>
      </form>
      <ul id="messages"></ul>
    </div>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      const socket = io();
    </script>
  </body>
</html>

This code creates a basic HTML page with a form for sending messages and a list for displaying the sent messages. It also includes the socket.io.js file, which is necessary to use Socket.io on the client side.

  1. Modify the code in server.js to handle the message send event and broadcast the message to all connected users:
io.on('connection', (socket) => {
  console.log('A user has connected');

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

  socket.on('disconnect', () => console.log('A user has disconnected'));
});
  1. Modify the code in index.html to handle the new message event and display the message in the list:
<!doctype html>
    <html>
        <head>
            <title>Chat App</title>
        </head>
        <body>
            <div id="chat">
                <form id="send-message">
                    <input type="text" placeholder="Type a message" />
                    <button>Send</button>
                </form>
                <ul id="messages"></ul>
            </div>
            <script src="/socket.io/socket.io.js"></script>
            <script>
                const socket = io();
                const form = document.getElementById('send-message');
                const messages = document.getElementById('messages');

                form.addEventListener('submit', (event)=> {
                    event.preventDefault();
                const input = form.querySelector('input');
                socket.emit('send message', input.value);
                input.value = '';
});

socket.on('new message', (message) => {
const li = document.createElement('li');
                li.innerText = message;
                messages.appendChild(li);
});
            </script>
        </body>
    </html>

Run the server using the command node server.js and open the index.html file in your browser. You should see a page with a form for sending messages and an empty list. Open multiple browser tabs or use different browsers to simulate multiple users connected to the chat. Each time you send a message, itshould appear in the list for all connected users.

That’s it! Now you have a basic chat application using JavaScript and Socket.io.

You can add more features, such as the option to send private messages or customize the page layout using CSS.

Leave a Comment