Language: EN

como-usar-socketio-con-nodejs

How to Use Socket.IO with Node.js

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

It uses WebSockets under the hood when available and provides an abstraction layer to handle real-time communication very easily for the developer.

Socket.IO Server Setup

Let’s start by setting up 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 set up 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 only for development testing!

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

  // Handle messages from the client
  socket.on('message', (message) => {
    console.log('Message received:', message);
    
    // Send message to all clients, including the one who sent the message
    io.emit('message', message);
  });

  // Handle 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.

We 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>

We 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, we create a JavaScript file to implement the client logic (client.js):

In this code, we establish a connection to 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 messages in real time in your chat.

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

Download the code

All the code for this entry is available for download on Github github-full