From 2f4fefd0f6a5c43724ee8d19b008018c28c7c323 Mon Sep 17 00:00:00 2001 From: andy finch Date: Wed, 1 May 2019 16:58:09 -0400 Subject: [PATCH] Async iterator for listener (#2263) --- js/net.ts | 15 ++++++++++++++- js/net_test.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/js/net.ts b/js/net.ts index 214da2927d..7bf6dc0982 100644 --- a/js/net.ts +++ b/js/net.ts @@ -14,7 +14,7 @@ export type Network = "tcp"; export type Addr = string; /** A Listener is a generic network listener for stream-oriented protocols. */ -export interface Listener { +export interface Listener extends AsyncIterator { /** Waits for and resolves to the next connection to the `Listener`. */ accept(): Promise; @@ -25,6 +25,8 @@ export interface Listener { /** Return the address of the `Listener`. */ addr(): Addr; + + [Symbol.asyncIterator](): AsyncIterator; } enum ShutdownMode { @@ -97,6 +99,17 @@ class ListenerImpl implements Listener { addr(): Addr { return notImplemented(); } + + async next(): Promise> { + return { + done: false, + value: await this.accept() + }; + } + + [Symbol.asyncIterator](): AsyncIterator { + return this; + } } export interface Conn extends Reader, Writer, Closer { diff --git a/js/net_test.ts b/js/net_test.ts index f02fa9611e..379f5c215f 100644 --- a/js/net_test.ts +++ b/js/net_test.ts @@ -72,6 +72,37 @@ testPerm({ net: true }, async function netDialListen(): Promise { conn.close(); }); +testPerm({ net: true }, async function netListenAsyncIterator(): Promise { + const listener = Deno.listen("tcp", ":4500"); + const runAsyncIterator = async (): Promise => { + for await (let conn of listener) { + await conn.write(new Uint8Array([1, 2, 3])); + conn.close(); + } + }; + runAsyncIterator(); + const conn = await Deno.dial("tcp", "127.0.0.1:4500"); + const buf = new Uint8Array(1024); + const readResult = await conn.read(buf); + assertEquals(3, readResult.nread); + assertEquals(1, buf[0]); + assertEquals(2, buf[1]); + assertEquals(3, buf[2]); + assert(conn.rid > 0); + + // TODO Currently ReadResult does not properly transmit EOF in the same call. + // it requires a second call to get the EOF. Either ReadResult to be an + // integer in which 0 signifies EOF or the handler should be modified so that + // EOF is properly transmitted. + assertEquals(false, readResult.eof); + + const readResult2 = await conn.read(buf); + assertEquals(true, readResult2.eof); + + listener.close(); + conn.close(); +}); + /* TODO Fix broken test. testPerm({ net: true }, async function netCloseReadSuccess() { const addr = "127.0.0.1:4500";