We are thrilled to inform you that Lancecourse is NOW INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for INITAcademy.org.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 95 – Creating a WebSocket Server and Client in JavaScript

In this lesson, we'll learn how to set up a WebSocket server and connect to it with a client using JavaScript. WebSockets allow for real-time communication between a browser and a server.

What You'll Learn

  • Setting up a basic WebSocket server (Node.js)
  • Connecting to the WebSocket server from a browser
  • Sending and receiving messages

1. Setting Up the WebSocket Server

We’ll use Node.js and the ws library to create a simple WebSocket server.

Step 1: Initialize a Node.js project

npm init -y
npm install ws

Step 2: Create the server (server.js)

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', ws => {
  console.log('Client connected');

  ws.on('message', message => {
    console.log(`Received: ${message}`);
    ws.send(`Echo: ${message}`); // Echo message back to client
  });

  ws.on('close', () => console.log('Client disconnected'));
});

2. Creating a WebSocket Client (Browser)

You can connect to the server using browser JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>WebSocket Client</title>
</head>
<body>
  <h1>WebSocket Client</h1>
  <input id="messageInput" type="text" placeholder="Type a message..." />
  <button onclick="sendMessage()">Send</button>
  <pre id="chatLog"></pre>

  <script>
    const socket = new WebSocket('ws://localhost:8080');
    const log = document.getElementById('chatLog');

    socket.onopen = () => {
      log.textContent += "Connected to WebSocket server\n";
    };

    socket.onmessage = (event) => {
      log.textContent += `Server: ${event.data}\n`;
    };

    function sendMessage() {
      const input = document.getElementById('messageInput');
      const message = input.value;
      socket.send(message);
      log.textContent += `You: ${message}\n`;
      input.value = '';
    }
  </script>
</body>
</html>

???? Run the Node.js server first using node server.js, then open the HTML file in your browser.


Summary

  • A WebSocket server listens for client connections and handles real-time communication.
  • The browser connects to the WebSocket and sends/receives messages asynchronously.
  • WebSockets are ideal for real-time apps like chats, games, and live updates.

Try It Yourself

  • Modify the server to broadcast messages to all connected clients.
  • Add a timestamp to messages in the client.
  • Handle error events (socket.onerror and socket.onclose).