1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-26 17:19:06 -05:00

Async iterator for listener (#2263)

This commit is contained in:
andy finch 2019-05-01 16:58:09 -04:00 committed by Ryan Dahl
parent 41c7e96f1a
commit 2f4fefd0f6
2 changed files with 45 additions and 1 deletions

View file

@ -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 {

View file

@ -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";