Created
November 30, 2018 08:47
-
-
Save geon/a8949fd34d0018462163674f1cad7350 to your computer and use it in GitHub Desktop.
How to build a socket server with async and for-await.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To test it, run
nc localhost 5555
and type stuff. Enter sends.ctrl+D
disconnects.