Skip to content

Instantly share code, notes, and snippets.

@mikilian
Created September 29, 2020 18:53
Show Gist options
  • Save mikilian/d4e36986d9cd2c19443ec5169f8fe838 to your computer and use it in GitHub Desktop.
Save mikilian/d4e36986d9cd2c19443ec5169f8fe838 to your computer and use it in GitHub Desktop.
node.js TCP client/server example
const { Socket } = require("net");
const tcpClient = (address, port, data) =>
new Promise((resolve, reject) => {
const client = new Socket();
client.connect({ port, address });
client.on("connect", () => {
client.write(Buffer.from(
typeof data === "string"
? data
: JSON.stringify(data)
));
client.end();
});
client.on("error", reject);
client.on("data", resolve);
})
const { createServer } = require("net");
const tcpServer = createServer(socket => {
socket.on("data", data => console.log(
`[>] server: ${data.toString()}`
));
socket.write("Pong!");
socket.pipe(socket);
});
tcpServer.listen(1339, "127.0.0.1", async () => {
const response = await tcpClient("127.0.0.1", 1339, "Ping");
console.log(`[<] client: ${response.toString()}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment