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 let’s 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.

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

npm install express socket.io http

Server Setup

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 messages from the client
  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 configure 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 the 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="Type 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 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 the terminal.

node server.js

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

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

Download the Code

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