Building a Chat Application with Socket.io

Tutorial 4 of 5

1. Introduction

In this tutorial, we'll be learning how to build a real-time chat application using Socket.io. This chat application will allow users to send and receive messages instantly.

You will learn how to:

  • Set up a server with Node.js and Express
  • Establish a real-time bi-directional communication between the server and the client with Socket.io
  • Broadcast messages to connected users

Prerequisites:

  • Basic knowledge of JavaScript
  • Node.js and npm installed on your machine

2. Step-by-Step Guide

2.1 Setting up the Server

We'll start by setting up a server using Node.js and Express. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

// Import express and create an app
const express = require('express');
const app = express();

// Define a route handler for the default home page
app.get('/', (req, res) => {
  res.send("Hello World!");
});

// Start the server on port 3000
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

2.2 Integrating Socket.io

Socket.io enables real-time, bidirectional and event-based communication. It works on every platform, browser, or device, focusing equally on reliability and speed.

// Import socket.io with a connection to a server obtained from a http server
var server = require('http').createServer(app);
var io = require('socket.io')(server);

// Listen on the connection event for incoming sockets
io.on('connection', (socket) => {
  console.log('a user connected');
});

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

3. Code Examples

3.1 Sending and Receiving Messages

Now we'll implement the core functionality of our chat app: sending and receiving messages.

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

  // Listen for chat message event
  socket.on('chat message', (msg) => {
    console.log('message: ' + msg);

    // Emit the message to all connected clients
    io.emit('chat message', msg);
  });
});

In this code snippet, we listen for the 'chat message' event, log the message to the console, and then emit the message to all connected clients.

3.2 Disconnecting a Socket

We also want to handle the case where a user disconnects from the chat.

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

  socket.on('chat message', (msg) => {
    console.log('message: ' + msg);
    io.emit('chat message', msg);
  });

  // Listen for disconnect event
  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

4. Summary

In this tutorial, we learned how to build a real-time chat application using Socket.io. We covered setting up a server with Node.js and Express, integrating Socket.io, and sending/receiving messages.

Next steps for learning would be to explore more features of Socket.io, like rooms and namespaces, and to experiment with storing messages in a database.

Additional resources include the Socket.io Documentation.

5. Practice Exercises

  1. Adding a username: Modify the chat app to include a username with each message.
  2. Private messages: Implement private messaging between two users.
  3. Chat history: Store chat history and display it to users when they join the chat.

Each of these exercises can be solved by applying what we've already learned and looking up additional information in the Socket.io documentation. For further practice, consider exploring other real-time data use-cases, like live updates in a dashboard application.