Tech Radioo

Your Daily Dose of Tech

Create a Web Socket Server with Socket.io and Node.js.

Creating a WebSocket server with socket.io and Node.js is a common task for building real-time web applications. Here’s a simple step-by-step guide to set up a WebSocket server using socket.io:

1. Install Node.js and Create a Project

First, ensure that Node.js is installed on your machine. If you haven’t set up a project, follow these steps:

  • Open a terminal and create a project folder.
$ mkdir websocket-server
$ cd websocket-server
  • Initialize a new Node.js project by running:
$ npm init -y
  • Install express and socket.io:
$ npm install express socket.io

2. Create a WebSocket Server

Next, let’s create a basic WebSocket server using socket.io and express.

index.js

Create a file called index.js in your project folder and paste the following code:

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

// Create an instance of express
const app = express();

// Create an HTTP server using the express app
const server = http.createServer(app);

// Initialize a new instance of socket.io by passing the server
const io = new Server(server);

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

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

  // Handle a message from the client
  socket.on('chat message', (msg) => {
    console.log('Message: ' + msg);
    
    // Broadcast the message to all connected clients
    io.emit('chat message', msg);
  });

  // Handle when the user disconnects
  socket.on('disconnect', () => {
    console.log('A user disconnected');
  });
});

// Start the server on port 3000
server.listen(3000, () => {
  console.log('WebSocket server running on http://localhost:3000');
});

3. Create a Client to Connect to the WebSocket

To test the WebSocket server, create an HTML file that will act as a simple client.

index.html

Create an index.html file in your project folder:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Socket.IO Chat</title>
  <style>
    ul { list-style-type: none; }
    li { padding: 8px; margin-bottom: 10px; background-color: #f4f4f4; }
    form { background: #333; padding: 3px; position: fixed; bottom: 0; width: 100%; }
    input { border: none; padding: 10px; width: 90%; margin-right: .5%; }
    button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 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();

    // Listen for chat messages from the server
    socket.on('chat message', function(msg){
      const item = document.createElement('li');
      item.textContent = msg;
      document.getElementById('messages').appendChild(item);
      window.scrollTo(0, document.body.scrollHeight);
    });

    // Send a chat message when the form is submitted
    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 = '';
      }
    });
  </script>
</body>
</html>

3. Run the WebSocket Server

After saving the files, start the server by running:

$ node index.js

The server should be running on http://localhost:3000.

5. Test the WebSocket

  • Open a browser and go to http://localhost:3000. You should see a chat interface.
  • Open multiple tabs or browsers, type messages, and watch them appear in all the connected clients in real-time.

Explanation

  • Server:
    • Uses express to serve an HTML file.
    • socket.io listens for WebSocket connections and messages, and emits messages to all connected clients.
  • Client:
    • The client listens for new messages from the server and displays them. It also allows users to send messages to the server via WebSocket.

This is a basic real-time chat server with WebSocket using socket.io and Node.js!

Leave a Reply

Your email address will not be published. Required fields are marked *