Deno World
Published in

Deno World

Deno nuggets: TCP client

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();

This story is a part of the exclusive medium publication on Deno: Deno World.

--

--

--

The one and only exclusive medium magazine with 200+ articles on Deno

Recommended from Medium

Using JWT (JSON Web Token) in Deno

Recharts — Radar and Radial Bar Charts

Using Event Handlers in JavaScript

Open Sourcing Violet — A Voice Application Framework

Create a Virtual Truth Game with JavaScript! | COM232

UI Development with Chakra UI Vue — Modals

UI Development with Chakra UI Vue — Tooltips

Deno nuggets: Overwrite a console log line

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mayank Choubey

Mayank Choubey

Deno, Node.js, etc.

More from Medium

JSON modules in Deno

3 ways of accepting self-signed certificates in Deno

Deno by example: Content server — Part 6 Deployment on Deno Deploy

HTTP/2 in Deno