sunichi sunichi - 4 months ago 8
Node.js Question

JavaScript file can't work while the code work with node in Terminal

I start a java client listening on localhost:8887
And I try this

var net = require('net')
var coon = net.connect(8887,'127.0.0.1')
coon.write('hi')
coon.destroy()


in Terminal with node. The client get the message.
Then I write it into a file test.js and use 'node test.js' in the Terminal, but the client can't get the message. How can I solve this problem.

I add
console.log(coon.remoteAddress+':'+coon.remotePort)
in the code. When I run 'node test.js', it shows that 'undefined:undefined'

Answer

Chances are you type into the terminal slow enough for the connection to be made. When you run the whole script, you're attempting to write before there is a connection.

Use the 3rd connectionListener argument

const coon = net.connect(8887, 'localhost', () => {
    coon.write('hi');
    coon.destroy();
});

See https://nodejs.org/api/net.html#net_net_connect_port_host_connectlistener

Comments