Language: EN

como-usar-socketio-con-nodejs

How to Use Socket.IO with Node.js

Socket.IO is a JavaScript library that enables bidirectional real-time communication between web clients and servers.

It uses WebSockets under the hood when available, and provides an abstraction layer for handling real-time communication in a very simple way for the developer.

Server Configuration for Socket.IO

Let’s start by configuring our Socket.IO server. We will use Node.js and Express.js to create the server.

First, we need to install the necessary dependencies. Run the following command in the terminal to install Express.js and Socket.IO:

npm install express socket.io

Setting up the server

Next, we will create a server.js file to configure our Socket.IO server.

import { createServer } from 'http';
import { Server as SocketIOServer } from 'socket.io';

const server = createServer();
const io = new SocketIOServer(server, { cors: { origin: '*' } }); // cors for development testing only!

// Handling client connections
io.on('connection', (socket) => {
  console.log('Client connected');

  // Handling client messages
  socket.on('message', (message) => {
    console.log('Received message:', message);
    
    // Send message to all clients, including the one that sent the message
    io.emit('message', message);
  });

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

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Socket.IO server started at http://localhost:${PORT}`);
});

In this code, we create an HTTP server and then set up Socket.IO to handle client connections, messages, and disconnections.

Creating the Web Client

Now, we will create the web client for our chat using HTML, CSS, and JavaScript.

Create an HTML file for the chat user interface.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Real-Time Chat with Socket.IO</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.5/socket.io.js" integrity="sha512-luMnTJZ7oEchNDZAtQhgjomP1eZefnl82ruTH/3Oj/Yu5qYtwL7+dVRccACS/Snp1lFXq188XFipHKYE75IaQQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>Real-Time Chat with Socket.IO</h1>
  <ul id="messages"></ul>
  <input type="text" id="message" placeholder="Type a message...">
  <button onclick="sendMessage()">Send</button>

  <script src="client.js"></script>
</body>
</html>

Create a CSS file to style our user interface (styles.css):

body {
  font-family: Arial, sans-serif;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin-bottom: 5px;
}

input[type="text"] {
  width: 200px;
  padding: 5px;
  margin-right: 5px;
}

button {
  padding: 5px 10px;
  cursor: pointer;
}

Finally, create a JavaScript file to implement the client logic (client.js):

In this code, we establish a connection with the Socket.IO server and define functions to send and receive messages from the server.

const socket = io.connect('http://localhost:3000');

// Send message to the server
function sendMessage() {
  const message = document.getElementById('message').value;
  socket.emit('message', message);
  document.getElementById('message').value = '';
}

// Receive messages from the server
socket.on('message', function(message) {
  const newMessage = document.createElement('li');
  newMessage.textContent = message;
  document.getElementById('messages').appendChild(newMessage);
});

Running the Application

To run the application, simply execute the server.js file in your terminal:

node server.js

Then, open the index.html file in a web browser. You should now be able to send and receive real-time messages in your chat.

Congratulations! You have successfully created a real-time chat using Socket.IO. Wasn’t it easy?