Blog>
Snippets

Online Auction System

Design an online auction system where bid updates are sent and received through WebSocket, keeping all participants in sync with current bids.
// Client-Side WebSocket Initialization
const auctionSocket = new WebSocket('wss://example.com/auction');

// Event handler for receiving messages
auctionSocket.onmessage = function(event) {
    const bidData = JSON.parse(event.data);
    updateBidOnUI(bidData);
};

// Function to update bid information on the web page
function updateBidOnUI(bidData) {
    document.getElementById('currentBid').textContent = bidData.newBid;
    document.getElementById('bidderName').textContent = bidData.bidderName;
}
This code initializes a WebSocket connection to the server, sets up an event handler for incoming messages, and updates the webpage's UI with the new bid data received.
// Function to send a new bid
function placeBid(bidAmount) {
    const bid = {
        newBid: bidAmount,
        bidderName: 'JohnDoe', // Replace with the actual bidder's name or ID
    };

    // Check if the WebSocket connection is open before sending data
    if (auctionSocket.readyState === WebSocket.OPEN) {
        auctionSocket.send(JSON.stringify(bid));
    } else {
        console.error('WebSocket connection is not open.');
    }
}
This code defines a function to place a new bid by sending the bid data through the WebSocket to the server. It checks if the connection is open before attempting to send data.
// Server-Side WebSocket Setup (using Node.js and ws library)
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

// Broadcast function to send messages to all connected clients
function broadcast(data) {
    wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(JSON.stringify(data));
        }
    });
}

// Event handler for connection
wss.on('connection', ws => {
    ws.on('message', message => {
        const bid = JSON.parse(message);
        // Handle new bid, such as saving to database or validating bid
        // After processing, broadcast new bid to all clients
        broadcast(bid);
    });
});
This server-side code uses the Node.js 'ws' library to set up a WebSocket server. It includes a broadcast function for sending messages to all connected clients and a connection event handler to receive and process new bids before broadcasting them.