Here is a simple example that creates a server and a client that connects to this server. Remember that what you send must be a buffer (lines are automatically converted to buffers). The client and server work independently of each other, so they can be placed in the same application or on completely different computers.
Server (server.js):
const net = require("net"); // Create a simple server var server = net.createServer(function (conn) { console.log("Server: Client connected"); // If connection is closed conn.on("end", function() { console.log('Server: Client disconnected'); // Close the server server.close(); // End the process process.exit(0); }); // Handle data from client conn.on("data", function(data) { data = JSON.parse(data); console.log("Response from client: %s", data.response); }); // Let response with a hello message conn.write( JSON.stringify( { response: "Hey there client!" } ) ); }); // Listen for connections server.listen(61337, "localhost", function () { console.log("Server: Listening"); });
Client (client.js):
const net = require("net"); // Create a socket (client) that connects to the server var socket = new net.Socket(); socket.connect(61337, "localhost", function () { console.log("Client: Connected to server"); }); // Let handle the data we get from the server socket.on("data", function (data) { data = JSON.parse(data); console.log("Response from server: %s", data.response); // Respond back socket.write(JSON.stringify({ response: "Hey there server!" })); // Close the connection socket.end(); });
The conn and socket objects implement the Stream interface.
source share