Deno is a modern runtime environment that supports TypeScript and provides robust built-in support for networking tasks, including the creation of TCP servers.
Step 1: Creating the TCP Server
First, we'll create a TCP server using Deno. Deno provides a net module in its standard library for building TCP servers. Below is the basic code for creating a simple TCP server:
javascript// Import Deno's network module import { listen } from "https://deno.land/std@0.145.0/net/mod.ts"; // Create the server listening on port 12345 const server = listen({ port: 12345 }); console.log("TCP server running on port 12345..."); for await (const conn of server) { handleConnection(conn); }
Step 2: Handling Connections
In the above code, we call the handleConnection function for each new connection. We must implement this function to process client data and logic.
javascriptasync function handleConnection(conn) { const buffer = new Uint8Array(1024); try { // Continuously read incoming data while (true) { const readResult = await conn.read(buffer); if (readResult === null) { break; // Connection has been closed } const message = new TextDecoder().decode(buffer); console.log("Received message:", message); // Echo the message back to the client await conn.write(new TextEncoder().encode("Message received: " + message)); } } catch (err) { console.error("Error handling connection:", err); } finally { // Close the connection conn.close(); } }
Step 3: Implementing Chat Functionality
To transform this into a chat server, we need to broadcast received messages to all connected clients. This can be achieved by maintaining a list of active connections.
javascriptconst connections = new Set(); async function handleConnection(conn) { connections.add(conn); const buffer = new Uint8Array(1024); try { while (true) { const readResult = await conn.read(buffer); if (readResult === null) { break; } const message = new TextDecoder().decode(buffer); console.log("Received message:", message); for (const conn of connections) { await conn.write(new TextEncoder().encode("Broadcast: " + message)); } } } catch (err) { console.error("Error handling connection:", err); } finally { conn.close(); connections.delete(conn); } }
Conclusion
The steps above outline how to create a basic TCP chat server with Deno. This server receives messages from clients and broadcasts them to all connected clients. Deno's net module simplifies TCP connection handling, making it intuitive and efficient. Such a server can serve as a foundation for various network applications, including game servers or real-time communication services.