Skip to content

Instantly share code, notes, and snippets.

@johnbender
Last active June 22, 2019 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnbender/adfa42f7341cdf2024025df4efb8a29c to your computer and use it in GitHub Desktop.
Save johnbender/adfa42f7341cdf2024025df4efb8a29c to your computer and use it in GitHub Desktop.
const net = require('net');
const EventEmitter = require('events');
class AsyncServer extends EventEmitter {
constructor(options){
super();
this._connections = [];
this._server = new net.Server();
this._options = options;
}
async listen() {
await new Promise((resolve) => {
this._server.listen(this._options, resolve);
});
this._server.on("connection", (c) => {
this._connections.push(c);
this.emit("connected");
})
}
connections() {
return {
[Symbol.asyncIterator]: () => {
return {
next: async () => {
// pop a connection
var connection = this._connections.shift();
// if it's empty wait until there's a connected client, then pop the connection
if(!connection) {
await new Promise((resolve) => this.once("connected", resolve));
var connection = this._connections.shift();
}
// return the connection
return {done: false, value: connection };
}
};
}
}
}
}
(async () => {
const server = await new AsyncServer({ host: 'localhost', port: 8124 });
await server.listen();
for await (var connection of server.connections()) {
// here we can choose to wait for async actions to complete
// with `await` or we can cast them off by calling them directly
// the loop will return to wait for connections either way
connection.write("foo\r\n");
}
})();
// $ telnet localhost 8124
// Trying ::1...
// telnet: connect to address ::1: Connection refused
// Trying 127.0.0.1...
// Connected to localhost.
// Escape character is '^]'.
// foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment