Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

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:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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'));
});
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')); });
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:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!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>
<!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>
<!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:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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'));
});
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')); });
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:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!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>
<!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>
<!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.

0

Leave a Comment