NodeJS - potatoscript/websocket GitHub Wiki

๐ŸŽฏ WebSocket with Node.js

๐Ÿ” 1. Introduction to Node.js WebSocket

Node.js is a powerful JavaScript runtime built on Chrome's V8 JavaScript engine. It is designed for building fast and scalable network applications, especially real-time applications like WebSocket-based communication systems.

WebSocket is a protocol that allows for two-way communication between a client (such as a web browser) and a server over a single, long-lived connection. WebSocket is ideal for real-time applications such as chat apps, online games, and live notifications.

In this tutorial, we will create a WebSocket server using Node.js and the ws package, which is a simple and efficient WebSocket library for Node.js.


๐Ÿ› ๏ธ 2. Setting up the WebSocket Server

Step 1: Install Node.js

Before we begin, you need to have Node.js installed. If you don't have it yet, download and install it from the official Node.js website.

Step 2: Install the ws library

The ws library is a simple WebSocket library for Node.js. To install it, open your terminal or command prompt and run the following command in your project folder:

npm init -y  # Initialize a new Node.js project
npm install ws  # Install the ws WebSocket library

Step 3: Create the WebSocket Server

Now, let's create a WebSocket server using the ws library.

Create server.js

Create a file called server.js and add the following code:

// Import the 'ws' module
const WebSocket = require('ws');

// Create a WebSocket server that listens on port 8080
const wss = new WebSocket.Server({ port: 8080 });

// When a client connects to the WebSocket server
wss.on('connection', (ws) => {
    console.log('A new client connected!');

    // Send a welcome message to the newly connected client
    ws.send('Welcome to the WebSocket server!');

    // When the server receives a message from the client
    ws.on('message', (message) => {
        console.log(`Received: ${message}`);

        // Send a response back to the client
        ws.send(`Server says: ${message}`);
    });

    // When the client disconnects
    ws.on('close', () => {
        console.log('A client disconnected');
    });
});

Explanation:

  1. WebSocket server setup: We first import the ws module and then create a WebSocket server that listens on port 8080. This means our server will accept WebSocket connections on ws://localhost:8080.

  2. Handling connections: When a client connects to the server, the 'connection' event is triggered. We send a welcome message to the client.

  3. Message handling: The server listens for incoming messages with the 'message' event. When a message is received, it sends a response back to the client.

  4. Client disconnection: The server listens for when the client disconnects with the 'close' event.


Step 4: Run the WebSocket Server

Now, let's run the WebSocket server.

Open the terminal and navigate to the directory where your server.js file is located, then run the following command:

node server.js

You should see the message WebSocket server running on ws://localhost:8080 indicating that the server is now running.


๐Ÿ—๏ธ 3. Testing the WebSocket Server

To test the WebSocket server, we need a WebSocket client. You can use a browser-based client or another Node.js application as a client.

For simplicity, weโ€™ll use an HTML file with JavaScript to create a client that connects to the WebSocket server.

Create a Simple WebSocket Client in HTML

Create an index.html file and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Client</title>
</head>
<body>
    <h2>WebSocket Client</h2>

    <!-- Message display area -->
    <div id="messages" style="height: 200px; width: 300px; overflow-y: scroll; border: 1px solid black; margin-bottom: 10px;">
    </div>

    <!-- Input for sending messages -->
    <input type="text" id="messageInput" placeholder="Type a message" />
    <button onclick="sendMessage()">Send Message</button>

    <script>
        // Create a new WebSocket connection to the server
        const socket = new WebSocket('ws://localhost:8080');

        // When the WebSocket connection is opened
        socket.onopen = () => {
            console.log('Connected to WebSocket server');
        };

        // When the WebSocket receives a message from the server
        socket.onmessage = (event) => {
            const messagesDiv = document.getElementById('messages');
            const newMessage = document.createElement('div');
            newMessage.textContent = event.data;
            messagesDiv.appendChild(newMessage); // Add the new message to the display area
        };

        // Function to send a message to the WebSocket server
        function sendMessage() {
            const message = document.getElementById('messageInput').value;
            if (message) {
                socket.send(message); // Send the message to the server
                document.getElementById('messageInput').value = ''; // Clear the input field
            }
        }
    </script>
</body>
</html>

Explanation:

  • The WebSocket('ws://localhost:8080') establishes a connection to the WebSocket server that is running on localhost at port 8080.
  • The onopen event triggers when the connection is successfully established.
  • The onmessage event handles incoming messages from the server and displays them in the messages div.
  • The sendMessage function sends the message typed in the input field to the WebSocket server.

Step 5: Test the WebSocket Communication

  1. Run the WebSocket Server: If it's not already running, start the server using the node server.js command.

  2. Open the HTML Client: Open the index.html file in your web browser.

  3. Send Messages: Type a message in the input field and click the "Send Message" button. The message will be sent to the server, and the server will respond with Server says: <your message>, which will be displayed in the messages div.


๐Ÿ”’ 4. Handling Client Disconnects

To handle when clients disconnect from the WebSocket server, you can use the 'close' event. Hereโ€™s an example of how to notify the server when a client disconnects:

wss.on('connection', (ws) => {
    console.log('A new client connected!');

    ws.on('close', () => {
        console.log('A client disconnected');
    });
});

The 'close' event fires when the client disconnects, either manually or due to network issues.


๐Ÿ”ง 5. Broadcasting Messages to All Clients

To broadcast messages to all connected clients, you can iterate over all WebSocket connections and send the message to each one. Hereโ€™s an example of how to do it:

wss.on('connection', (ws) => {
    console.log('A new client connected!');

    ws.on('message', (message) => {
        console.log(`Received: ${message}`);
        
        // Broadcast the message to all connected clients
        wss.clients.forEach((client) => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(message);
            }
        });
    });
});

Explanation:

  • wss.clients contains all connected clients.
  • We loop through each client and send the message to all other clients except the one that sent the message.

๐Ÿ” 6. Conclusion

In this tutorial, weโ€™ve covered the following:

  • How to set up a WebSocket server in Node.js using the ws library.
  • How to create a WebSocket client in HTML and JavaScript.
  • How to handle messages between the client and server.
  • How to handle client disconnects and broadcast messages to all connected clients.
โš ๏ธ **GitHub.com Fallback** โš ๏ธ