diff options
author | andy finch <andyfinch7@gmail.com> | 2019-05-01 16:58:09 -0400 |
---|---|---|
committer | Ryan Dahl <ry@tinyclouds.org> | 2019-05-01 16:58:09 -0400 |
commit | 2f4fefd0f6a5c43724ee8d19b008018c28c7c323 (patch) | |
tree | 1566f5e0ed9f5cb5c3ba2067263431c32f5f5df1 | |
parent | 41c7e96f1a81ea416ebb3ba45f2815e0202d6b75 (diff) |
Async iterator for listener (#2263)
-rw-r--r-- | js/net.ts | 15 | ||||
-rw-r--r-- | js/net_test.ts | 31 |
2 files changed, 45 insertions, 1 deletions
@@ -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<Conn> { /** Waits for and resolves to the next connection to the `Listener`. */ accept(): Promise<Conn>; @@ -25,6 +25,8 @@ export interface Listener { /** Return the address of the `Listener`. */ addr(): Addr; + + [Symbol.asyncIterator](): AsyncIterator<Conn>; } enum ShutdownMode { @@ -97,6 +99,17 @@ class ListenerImpl implements Listener { addr(): Addr { return notImplemented(); } + + async next(): Promise<IteratorResult<Conn>> { + return { + done: false, + value: await this.accept() + }; + } + + [Symbol.asyncIterator](): AsyncIterator<Conn> { + return this; + } } export interface Conn extends Reader, Writer, Closer { diff --git a/js/net_test.ts b/js/net_test.ts index f02fa9611..379f5c215 100644 --- a/js/net_test.ts +++ b/js/net_test.ts @@ -72,6 +72,37 @@ testPerm({ net: true }, async function netDialListen(): Promise<void> { conn.close(); }); +testPerm({ net: true }, async function netListenAsyncIterator(): Promise<void> { + const listener = Deno.listen("tcp", ":4500"); + const runAsyncIterator = async (): Promise<void> => { + 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"; |