2020-09-12 08:03:18 -04:00
|
|
|
# TCP echo server
|
|
|
|
|
|
|
|
## Concepts
|
|
|
|
|
|
|
|
- Listening for TCP port connections with
|
2020-09-27 13:49:41 -04:00
|
|
|
[Deno.listen](https://doc.deno.land/builtin/stable#Deno.listen).
|
2020-09-12 08:03:18 -04:00
|
|
|
- Use [Deno.copy](https://doc.deno.land/builtin/stable#Deno.copy) to take
|
2020-09-27 13:49:41 -04:00
|
|
|
inbound data and redirect it to be outbound data.
|
2020-09-12 08:03:18 -04:00
|
|
|
|
|
|
|
## Example
|
2020-05-06 18:21:13 -04:00
|
|
|
|
2020-05-26 10:08:23 -04:00
|
|
|
This is an example of a server which accepts connections on port 8080, and
|
|
|
|
returns to the client anything it sends.
|
2020-05-06 18:21:13 -04:00
|
|
|
|
|
|
|
```ts
|
2020-09-12 08:03:18 -04:00
|
|
|
/**
|
|
|
|
* echo_server.ts
|
|
|
|
*/
|
2020-05-06 18:21:13 -04:00
|
|
|
const listener = Deno.listen({ port: 8080 });
|
|
|
|
console.log("listening on 0.0.0.0:8080");
|
|
|
|
for await (const conn of listener) {
|
2021-01-05 06:09:50 -05:00
|
|
|
Deno.copy(conn, conn).finally(() => conn.close());
|
2020-05-06 18:21:13 -04:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2020-09-12 08:03:18 -04:00
|
|
|
Run with:
|
2020-05-06 18:21:13 -04:00
|
|
|
|
|
|
|
```shell
|
2020-09-12 08:03:18 -04:00
|
|
|
deno run --allow-net echo_server.ts
|
2020-05-06 18:21:13 -04:00
|
|
|
```
|
|
|
|
|
2020-09-12 08:03:18 -04:00
|
|
|
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:
|
2020-05-06 18:21:13 -04:00
|
|
|
|
|
|
|
```shell
|
|
|
|
$ nc localhost 8080
|
|
|
|
hello world
|
|
|
|
hello world
|
|
|
|
```
|
|
|
|
|
2020-09-12 08:03:18 -04:00
|
|
|
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.
|