TCP echo server

Concepts

  • Listening for TCP port connections with Deno.listen
  • Use Deno.copy to take inbound data and redirect it to be outbound data

Example

This is an example of a server which accepts connections on port 8080, and returns to the client anything it sends.

  1. /**
  2. * echo_server.ts
  3. */
  4. const listener = Deno.listen({ port: 8080 });
  5. console.log("listening on 0.0.0.0:8080");
  6. for await (const conn of listener) {
  7. Deno.copy(conn, conn);
  8. }

Run with:

  1. deno run --allow-net echo_server.ts

To test it, try sending data to it with netcat (Linux/MacOS only). Below 'hello world' is sent over the connection, which is then echoed back to the user:

  1. $ nc localhost 8080
  2. hello world
  3. hello world

Like the cat.ts example, the copy() function here also does not make unnecessary memory copies. It receives a packet from the kernel and sends back, without further complexity.