summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--js/net.ts15
-rw-r--r--js/net_test.ts31
2 files changed, 45 insertions, 1 deletions
diff --git a/js/net.ts b/js/net.ts
index 214da2927..7bf6dc098 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<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";