Skip to main content

The development of real time tools has increased among modern web professionals. WebSockets is a useful tool that enables real time communication between clients and servers, whether you are developing a communication image tool, a live chat application, or a collaborative document editor In this article we will walk you through a they use WebSockets to make it into real time collaboration software.

How does WebSockets work?

WebSockets are a complete dual communication mechanism over a single long-lived connection, allowing clients and servers to exchange data in real time. WebSockets are ideal for applications that need to be updated immediately because they allow two-way communication, which is not possible with ordinary HTTP requests.

Prerequisites

Before we begin the tutorial, make sure you have the following prerequisites.

  • Basic knowledge of HTML, CSS, and JavaScript.
  • Node.js and npm installed on your development machine.

Step 1: Set Up Your Project

Create a new project directory and initialize a Node.js project. Open your terminal and run the following commands:

mkdir collab-app
cd collab-app
npm init -y

Install the necessary packages:

npm install express socket.io

Create an index.js file to start building your server:

// index.js

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

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

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

server.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Step 2: Create the HTML file

Create a simple HTML file (index.html) to serve as the entry point for your application:

<!-- index.html -->

<!-- ... (previous HTML code) -->

<body>
  <h1>Welcome to the Collab App</h1>

  <!-- Form for setting the username -->
  <form id="username-form">
    <label for="username">Enter your username:</label>
    <input type="text" id="username" required>
    <button type="submit">Set Username</button>
  </form>

  <!-- Your collaborative app interface goes here -->
  <div id="messages-container"></div>
  <form id="message-form">
    <input type="text" id="message-input" placeholder="Type your message..." required>
    <button type="submit">Send</button>
  </form>

  <script src="/socket.io/socket.io.js"></script>
  <script src="/main.js"></script>
</body>

Step 3: Implement WebSocket Communication

Create a main.js file to handle WebSocket communication:

// main.js

const socket = io();

// DOM elements
const messageForm = document.getElementById('message-form');
const messageInput = document.getElementById('message-input');
const messagesContainer = document.getElementById('messages-container');

// Function to append messages to the UI
function appendMessage(username, message) {
  const messageElement = document.createElement('div');
  messageElement.innerHTML = `<strong>${username}:</strong> ${message}`;
  messagesContainer.appendChild(messageElement);
}

// Event listener for form submission (sending messages)
messageForm.addEventListener('submit', (event) => {
  event.preventDefault();
  const message = messageInput.value.trim();
  if (message !== '') {
    socket.emit('message', message);
    appendMessage('You', message); // Display the sent message immediately
    messageInput.value = ''; // Clear the input field
  }
});

// Handle a new user joining
socket.on('user joined', (username) => {
  appendMessage('System', `${username} joined the collaboration`);
});

// Handle receiving messages
socket.on('message', (data) => {
  appendMessage('User', data); // Assuming all received messages are from a user named 'User'
});

Extend your index.js file to handle WebSocket connections:

// index.js

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

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

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

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

const users = new Map(); // Map to store connected users and their corresponding sockets

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

  // Prompt the user for their username
  socket.emit('message', 'Please enter your username.');

  // Handle setting and broadcasting usernames
  socket.on('setUsername', (username) => {
    users.set(socket.id, username);
    socket.emit('message', `Welcome to the collaboration, ${username}!`);
    socket.broadcast.emit('user joined', username);
  });

  // Handle messages from clients
  socket.on('message', (data) => {
    const username = users.get(socket.id) || 'Anonymous';
    io.emit('message', `${username}: ${data}`);
  });

  // Handle disconnection
  socket.on('disconnect', () => {
    const username = users.get(socket.id) || 'Anonymous';
    users.delete(socket.id);
    io.emit('message', `${username} left the collaboration`);
  });
});

const PORT = process.env.PORT || 3000;

server.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Step 4: Run Your Application

Back in your terminal, run the following command to start your server:

node index.js

Visit http://localhost:3000 in your web browser to see your real time collaborative app in action.

We sincerely hope you enjoyed reading this post. Although this tutorial is minimal, you may make your application better by including features like file sharing, user authentication and cooperation exchange. There are countless ways to develop dynamic real time web tools with WebSockets. Have fun with coding!