Building a Deno Chat App with WebSockets: A Quick Guide

93 views

Creating a chat application using Deno and WebSockets involves setting up a WebSocket server to manage connections and communication between clients. Below is a simple example demonstrating how to implement a basic chat application using Deno’s native WebSocket API.

Setting Up the Server

First, create a server that handles WebSocket connections and relays messages between clients.

import { WebSocketServer } from "https://deno.land/std@0.119.0/ws/mod.ts";

// Create a WebSocket server that listens on a specific port
const port = 8080;
const wss = new WebSocketServer(port);
console.log(`WebSocket server is running on ws://localhost:${port}`);

wss.on("connection", (ws: WebSocket) => {
  console.log("Client connected!");

  // Broadcast incoming messages to all connected clients
  ws.on("message", async (message: string) => {
    for (const client of wss.clients) {
      if (client !== ws && client.isOpen) {
        client.send(message);
      }
    }
  });

  ws.on("close", () => {
    console.log("Client disconnected!");
  });
});

Setting Up the Client

Next, create an HTML file with a client-side script to connect to the WebSocket server and handle chat messages.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Chat Application</title>
  <style>
    #chat {
      height: 300px;
      overflow-y: scroll;
      border: 1px solid #ccc;
      padding: 10px;
    }
  </style>
</head>
<body>
  <h1>WebSocket Chat</h1>
  <div id="chat"></div>
  <input type="text" id="message" placeholder="Type a message" autofocus />
  <button id="send">Send</button>

  <script>
    const chatDiv = document.getElementById('chat');
    const messageInput = document.getElementById('message');
    const sendButton = document.getElementById('send');

    const ws = new WebSocket('ws://localhost:8080');

    ws.onmessage = (event) => {
      const newMessage = document.createElement('div');
      newMessage.textContent = event.data;
      chatDiv.appendChild(newMessage);
      chatDiv.scrollTop = chatDiv.scrollHeight; // Auto-scroll to the latest message
    };

    sendButton.onclick = () => {
      const message = messageInput.value;
      if (message) {
        ws.send(message);
        messageInput.value = '';
      }
    };

    messageInput.onkeypress = (event) => {
      if (event.key === 'Enter') {
        sendButton.click();
      }
    };
  </script>
</body>
</html>

Running the Application

  1. Start the Deno WebSocket Server: Make sure Deno is installed on your system, and run the server script with the following command:

    deno run --allow-net server.ts
    
  2. Open the HTML File: Open the index.html file in a web browser. Multiple clients can be opened in different tabs or windows to simulate multiple users in the chat.

Explanation

  • WebSocket Server: This server accepts connections and listens for messages. When a message is received, it is broadcast to all clients except the sender.
  • WebSocket Client: The client connects to the WebSocket server and can send messages using a simple input form.
  • Communication: The real-time communication is handled through WebSockets, allowing messages to be sent and received instantly without page reloads.

This example forms a basic chat application foundation, and you can expand upon it by adding user authentication, message history, and other features as needed.