Skip to content

Instantly share code, notes, and snippets.

@geon
Created November 30, 2018 08:47
Show Gist options
  • Save geon/a8949fd34d0018462163674f1cad7350 to your computer and use it in GitHub Desktop.
Save geon/a8949fd34d0018462163674f1cad7350 to your computer and use it in GitHub Desktop.
How to build a socket server with async and for-await.
import { createServer, Socket } from "net";
// Promisified socket.write().
const write = (socket: Socket, data: Buffer | string) =>
new Promise((resolve, reject) =>
socket.write(data as Buffer, (error: Error | undefined) => {
if (error) {
reject();
} else {
resolve();
}
}),
);
const server = createServer(async socket => {
console.log("Client connected.");
socket.on("end", () => console.log("Client disconnected."));
try {
// Loop asynchronously over incoming network packages.
for await (const buffer of socket) {
// Echo.
await write(socket, buffer.toString());
// Simulate server errors.
if (Math.random() > 0.75) {
throw new Error("Simulated server error.");
}
}
} catch (error) {
// Error handling.
socket.end();
console.error("Connection terminated due to error.");
}
});
server.listen(5555);
@geon
Copy link
Author

geon commented Dec 14, 2018

To test it, run nc localhost 5555 and type stuff. Enter sends. ctrl+D disconnects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment