Building a Real-Time Chat Application with Socket.IO and Electron: From Web to Desktop

πŸ’¬

Real-Time Chat Application

Socket.IO + Electron: From Web to Desktop

Build a real-time chat application using Socket.IO and convert it into a desktop application using Electron. Learn how to create instant messaging with modern web technologies.

Real-time communication is at the core of many modern applications, especially for chat platforms. Whether it's messaging apps, collaborative tools, or customer support systems, the ability to communicate instantly is key.

In this article, we will build a simple chat component using Socket.IO, integrate it into a web application, and then convert that web app into a desktop application using Electron. We will also share the full code on GitHub for you to try out!

πŸ“‹

Prerequisites

What you need to get started

πŸ“‹

Before we dive in, make sure you have the following tools and knowledge ready:

  • Basic knowledge of JavaScript and Node.js
  • Installed Node.js and npm on your machine
  • Basic understanding of Socket.IO
  • Familiarity with Electron is a plus, but not required

To install Node.js, visit nodejs.org and download the latest version. You can check your installation by running:

BASH
node -v
npm -v
🌐

Setting Up the Web App with Socket.IO

Create a real-time web application

First, we will create a simple web application that allows users to send and receive messages in real-time. This will serve as the foundation for our desktop application.

1

Initialize the Project

Create a new directory for your chat app and initialize it as a Node.js project:

BASH
mkdir socket-io-chat
cd socket-io-chat
npm init -y
2

Install Dependencies

Next, install the required dependencies: Express and Socket.IO.

BASH
npm install express socket.io
3

Create the Server

Now, we will create the Express server and set up Socket.IO to handle real-time communication.

Create a server.js file:

JAVASCRIPT
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

// Handle connection and message events
io.on('connection', (socket) => {
  console.log('a user connected');
  
  socket.on('chat message', (msg) => {
    io.emit('chat message', msg);
  });

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

server.listen(3000, () => {
  console.log('listening on *:3000');
});
4

Create the Frontend (HTML)

Create an index.html file in the same directory:

HTML
<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO Chat</title>
    <style>
      body { font-family: Arial, sans-serif; }
      ul { list-style-type: none; margin: 0; padding: 0; }
      li { padding: 8px; background-color: #f4f4f4; margin-bottom: 10px; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form id="form" action="">
      <input id="input" autocomplete="off" /><button>Send</button>
    </form>

    <script src="/socket.io/socket.io.js"></script>
    <script>
      const socket = io();

      const form = document.getElementById('form');
      const input = document.getElementById('input');

      form.addEventListener('submit', function(e) {
        e.preventDefault();
        if (input.value) {
          socket.emit('chat message', input.value);
          input.value = '';
        }
      });

      socket.on('chat message', function(msg) {
        const item = document.createElement('li');
        item.textContent = msg;
        document.getElementById('messages').appendChild(item);
      });
    </script>
  </body>
</html>
5

Run the Web Application

Now, let's run our web application:

BASH
node server.js

Open your browser and navigate to http://localhost:3000. Open two browser windows and see the real-time communication between them!

πŸ–₯️

Converting to Desktop App with Electron

Transform your web app into a desktop application

Now that we have a fully functional web-based chat app, let's convert it into a desktop application using Electron. This will allow users to run your chat app as a standalone desktop application.

1

Install Electron

Install Electron globally or locally within your project:

BASH
npm install electron --save-dev
2

Create the Electron Main File

Create a new file called main.js for Electron:

JAVASCRIPT
const { app, BrowserWindow } = require('electron');
const path = require('path');

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    }
  });

  win.loadURL('http://localhost:3000');
}

app.whenReady().then(() => {
  createWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
3

Add Electron Scripts to package.json

Update your package.json file with Electron's start script:

JSON
"scripts": {
  "start": "node server.js",
  "electron": "electron ."
}
4

Run the Desktop Application

Now, start both the server and the Electron application:

BASH
npm run start
npm run electron

You should see your chat application open in a standalone desktop window.

πŸš€

GitHub Repository

You can find the complete source code for this project with all the examples and additional features on GitHub.

🎯

Conclusion

What you've accomplished and next steps

In this article, we've successfully built a simple real-time chat application using Socket.IO and converted it into a desktop app using Electron. By leveraging Electron, we transformed our web application into a cross-platform desktop application with minimal changes to the codebase.

This approach allows you to maintain a single codebase while providing both web and desktop experiences. You can extend this foundation with features like user authentication, message persistence, file sharing, and more.

πŸ”§ Next Steps

Add user authentication, message persistence, and advanced features to make your chat app production-ready.

πŸ“š Learn More

Explore Socket.IO's advanced features and Electron's APIs for building more sophisticated applications.