Deno nuggets: TCP client

Mayank Choubey
Tech Tonic
2 min readJan 21, 2022

--

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to write a TCP client in Deno?

$ telnet 0.0.0.0 8888
Trying 0.0.0.0...
Connected to 0.0.0.0.
Escape character is '^]'.
From Client: 1
From Server: 2
From Client: 3
From Server: 4
Connection closed by foreign host.

Solution

Deno’s core runtime comes with connect, read, write, and close APIs to create a TCP client.

Imports

No imports are required.

TCP client

  • TCP APIs work with byte arrays (Uint8Array). It is useful to write encode and decode utility functions that internally uses TextEncoder and TextDecoder.
const encoder = new TextEncoder(), 
decoder = new TextDecoder();
const enc = (d: string) => encoder.encode(d),
dec = (b: Uint8Array) => decoder.decode(b);
  • The connect() API can be used to initiate and establish a TCP connection with a TCP server. It returns a Deno.Conn object that contains socket information.
const conn = await Deno.connect({ port: 8888 });conn.localAddr; //{ transport: "tcp", hostname: "127.0.0.1", port: 50094 }
conn.remoteAddr; //{ transport: "tcp", hostname: "127.0.0.1", port: 8888 }
conn.rid; //3
  • The write() API can be used to send data on the TCP socket. The data must be in bytes format (Uint8Array). It returns the number of bytes successfully sent over the socket.
const n=await conn.write(enc('From client: 1'));
n; //14
  • The read() API (blocking) can be used to wait for data from the TCP socket. It returns the number of bytes read from the socket. Like write() API, the data is filled in a byte array (Uint8Array).
const buf = new Uint8Array(100);
await conn.read(buf);
dec(buf); //From server: 2
  • The close() API can be used to terminate the TCP connection.
conn.close();

Complete Example

The following is the code of a TCP chat client that connects to a server, takes client inputs, waits for server responses, and quits when the user doesn’t enter anything.

const encoder = new TextEncoder(), decoder = new TextDecoder();
const enc = (d: string) => encoder.encode(d),
dec = (b: Uint8Array) => decoder.decode(b);
const buf = new Uint8Array(100);
const conn = await Deno.connect({ port: 8888 });
console.log("Connected to server", conn.remoteAddr);
while (1) {
const inp = prompt("Client > ") || "";
if (!inp) break;
await conn.write(enc(inp));
await conn.read(buf);
console.log("Server >", dec(buf));
}
console.log("Client exiting ...");
conn.close();

--

--