BeginnerCoder
intermediate#Socket.io#Real-time#Node.js

Introduction to Socket.io

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Learn the basics of Socket.io, and create a simple real-time chat application.

Introduction to Socket.io

Socket.io is a JavaScript library that enables real-time communication between web clients and servers. It's a popular choice for building real-time web applications, such as chat apps, live updates, and more.

Installing Socket.io

To get started with Socket.io, you need to have Node.js and npm installed on your computer. You also need to install the Socket.io library. You can install these dependencies by running the following command:

npm install socket.io

Creating a Server

To create a server, you can use the following code:

const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);

let messages = [];

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

socket.on('message', (message) => {
    messages.push(message);
    io.emit('message', message);
  });
});

server.listen(3000, () => {
  console.log('Server started on port 3000');
});

Creating a Client

To create a client, you can use the following code:

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

socket.on('message', (message) => {
  console.log(`Received message: ${message}`);
});

socket.emit('message', 'Hello from client!');

You can then use this chat application to send and receive messages in real-time.

Keep going with Socket.io

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.