Skip to content
This repository has been archived by the owner on Sep 21, 2023. It is now read-only.

Latest commit

 

History

History
40 lines (32 loc) · 1.39 KB

tcp_server.md

File metadata and controls

40 lines (32 loc) · 1.39 KB

TCP server

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

import { copy } from "https://deno.land/std@$STD_VERSION/streams/conversion.ts";
const hostname = "0.0.0.0";
const port = 8080;
const listener = Deno.listen({ hostname, port });
console.log(`Listening on ${hostname}:${port}`);
for await (const conn of listener) {
  copy(conn, conn);
}

For security reasons, Deno does not allow programs to access the network without explicit permission. To allow accessing the network, use a command-line flag:

deno run --allow-net https://deno.land/std@$STD_VERSION/examples/echo_server.ts

To test it, try sending data to it with netcat (or telnet on Windows):

Note for Windows users: netcat is not available on Windows. Instead you can use the built-in telnet client. The telnet client is disabled in Windows by default. It is easy to enable however: just follow the instructions on Microsoft TechNet

# Note for Windows users: replace the `nc` below with `telnet`
$ nc localhost 8080
hello world
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 it back, without further complexity.