Question

I created a simple tcp server using code

var net = require('net');

// Setup a tcp server
var server = net.createServer(function (socket) {

  socket.addListener("connect", function () {
    console.log('hello');
    sys.puts("Connection from " + socket.remoteAddress);
    socket.end("Hello World\n");
  });

});

server.listen(7000, "127.0.0.1");


console.log("TCP server listening on port 7000 at 127.0.0.1");

It started successfully, but how can I send some test msg to that tcp server, I tried SocketTest v.3 but not console output. enter image description here

Was it helpful?

Solution

Use data event handler to receive data in the server.

socket.on('data', function(data) {        
  console.log(data);
  // echo back
  socket.write('You said '+data);        
});

OTHER TIPS

For people still looking for answers, here's how I did it with SocketTest

const net = require('net');

const client = new net.Socket();

const HOST = "127.0.0.1";
const PORT = 7000;

client.on('data', () => {
    client.destroy(); // kill after response
});

client.on('error', () => {
    client.destroy(); // kill
});

client.connect(PORT, HOST, () => {
    client.write('Hello world!');
    client.end();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top