Language: EN

como-usar-socketio-y-express-nodejs

How to use Socket.IO and Express.js with Node.js

We have already seen how to use express.js and socket.iop separately. The good news is that both pieces fit perfectly into your project.

So now we are going to see how to combine Express.js and Socket.IO. As an example, we will create a real-time chat.

We will use Express to serve the web application and Socket.IO for bidirectional communication between clients and the server.

How to use Express with Socket.IO

We will start by setting up our server using Express.js and Socket.IO. First, we need to install the necessary dependencies.

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

npm install express socket.io http

Server Configuration

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

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

const app = express();
const server = http.createServer(app);
const io = new SocketIOServer(server, { cors: { origin: '*' } }); // cors only for testing in the example!

// Serve static files from the 'public' folder
app.use(express.static('public'));

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

  // Handle client messages
  socket.on('message', (message) => {
    console.log('Message received:', message);
    
    // Send message to all clients, including the one that 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 set up an Express server and create an HTTP server using the http module. Then, we set up a Socket.IO server on the same HTTP server instance.

Additionally, we use Express to serve static files from the public folder.

Creating the Web Client

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

Step 1: Create the User Interface

We create a simple web page for the chat user interface. All files will be saved in the public folder of the project.

On one hand, we create an HTML file for the chat user interface.

<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>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>
  <script src="client.js"></script>
</head>
<body>
  <h1>Chat with Socket.IO</h1>
  <ul id="messages"></ul>
  <input type="text" id="message" placeholder="Write a message...">
  <button onclick="sendMessage()">Send</button>
</body>
</html>

Finally, we create a JavaScript file to implement the client logic. 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 the terminal.

node server.js

On the other hand, open the web browser and enter http://localhost:3000 as the address to access the chat.

Express.js will serve the web page we have in public. Through socket.io, we can send and receive real-time messages in its chat.