I have created a tcp server and a tcp client.
In my tcp client, I have specified the localPort because I want to use some specific ports in case of reconnection.
Below is my tcp server and client's code
TCP SERVER
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
socket.on('error', function(err){
console.log('on socket error', err);
})
});
server.on('error', function(err){
console.log('on error',err);
})
server.listen(1337, '127.0.0.1');
TCP CLIENT
var net = require('net');
var client = new net.Socket();
client.connect({port: 1337, host: '127.0.0.1', localPort: 10002}, function() {
console.log('Connected');
client.write('Hello, server! Love, Client.');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
client.on('error', function(err) {
console.log('error in connection',err);
});
I have this server and client in two separate files. If I run the server, and then run the client for the first time, everything works fine. But as soon as I re-run(reconnect) the client, it gives me an error
{ Error: connect EADDRINUSE 127.0.0.1:1337 - Local (0.0.0.0:10002)
at internalConnect (net.js:964:16)
at defaultTriggerAsyncIdScope (internal/async_hooks.js:281:19)
at net.js:1062:9
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickCallback (internal/process/next_tick.js:181:9)
at Function.Module.runMain (module.js:696:11)
at startup (bootstrap_node.js:204:16)
at bootstrap_node.js:625:3
errno: 'EADDRINUSE',
code: 'EADDRINUSE',
syscall: 'connect',
address: '127.0.0.1',
port: 1337 }
It works fine if I retry after around 30 seconds.
Does net in nodejs have a TIMEOUT of not using the same localPort for 30 seconds? If it is so, can we reduce it or manage it somehow?