Created
September 29, 2020 18:53
-
-
Save mikilian/d4e36986d9cd2c19443ec5169f8fe838 to your computer and use it in GitHub Desktop.
node.js TCP client/server example
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
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); | |
}) |
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
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