summaryrefslogtreecommitdiff
path: root/docs/examples/tcp_echo.md
blob: f016b8bd8455576ba28a2fc2aae5813420a3d77e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# TCP echo server

## Concepts

- Listening for TCP port connections with
  [Deno.listen](https://doc.deno.land/builtin/stable#Deno.listen).
- Use
  [copy](https://doc.deno.land/https/deno.land/std@$STD_VERSION/io/util.ts#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.

```ts
/**
 * echo_server.ts
 */
import { copy } from "https://deno.land/std@$STD_VERSION/io/util.ts";
const listener = Deno.listen({ port: 8080 });
console.log("listening on 0.0.0.0:8080");
for await (const conn of listener) {
  copy(conn, conn).finally(() => conn.close());
}
```

Run with:

```shell
deno run --allow-net echo_server.ts
```

To test it, try sending data to it with
[netcat](https://en.wikipedia.org/wiki/Netcat) (Linux/MacOS only). Below
`'hello world'` is sent over the connection, which is then echoed back to the
user:

```shell
$ nc localhost 8080
hello world
hello world
```

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