getConnections method of node.js tcp server not defined - node.js

var server = net.createServer(function(c) {
...
})
server.getConnections(function(err, count){
console.log("count", count);
})
I get the following error.
Object #<Server> has no method 'getConnections'
How to use getConnections of a tcp server?
I'm using node version v0.10.16

I'm not sure exactly why your code doesn't work. While having the request to getConnections outside of the connection callback is not necessary typical, it worked in my tests. server.connections is deprecated per the documentation, so it's use is discouraged.
Using telnet localhost 1337, a really poor echo socket is emulated below, and the current count of connections is displayed. The code below worked in my tests:
var server = require('net').createServer();
server.on('connection', function (socket) {
socket.on('data', function(data) {
socket.write(data);
});
server.getConnections(function(err, count) {
console.log("Connections: " + count);
});
});
server.listen(1337);

You can try like this:
var net = require('net');
var events = require('events');
var eventEmitter = new events.EventEmitter();
var server = net.createServer(function(c) {
...`enter code here`
eventEmitter.emit('event1');
})
eventEmitter.on('event1', function(){
server.getConnections(function(err, count){
console.log("count", count);
})
});

Related

NodeJS net module - don't try to create another instance of TCP server when called again

I'm totally new to the whole nodeJS asynchronous-y callback-y programming so I need more like a guidance to understanding what I'm even doing. With that said, I have two files main.js and server.js
My main file looks like this:
var server=require('./server.js');
server();
function WhenUserClicksButton(){
server();
}
and my server file looks like this:
var net = require('net');
function server(){
net.createServer(function (socket) {
socket.write('\x16'); //SYN character
socket.on('data', function (data) {
//handle data from client
});
}).listen(33333);
}
First call of server(); starts the TCP server. Then function WhenUserClicksButton is called when user clicks button (duhh) in a GUI. But it attempts to start the server again so I get
Error: listen EADDRINUSE :::33333
I got why this is happening but I can't think of a solution for it. What I really need is:
Start the server and listen on 33333
When nothing is happening server and client just exchanges SYN and ACK characters every few seconds (I already have this part done, I just removed it from this example for clarity because it's not really topic of this question)
When user click button change socket.write('\x16'); to socket.write('something');
Then wait for server and client to exchange data and after everything is done return results back to main.js
As I said, I'm new to this and I believe my problem lies in not understanding fully of what I'm doing. Any help and explanations are welcome!
I think you're very near where you need to be. I would do something like this:
server.js
var net = require('net');
var netServer = null;
var netSocket = null;
function sendData(data) {
if (netServer && netSocket) {
console.log('Send data: sending: ', data);
netSocket.write(data);
}
}
function startServer(){
netServer = net.createServer(function (socket) {
netSocket = socket;
socket.write('\x16'); //SYN character
socket.on('data', function (data) {
console.log('Server: data from client: ', data);
if (data.length === 1 && data[0] === 0x16) {
// log and ignore SYN chars..
console.log('SYN received from client');
} else if (newDataCallback) {
newDataCallback(data);
};
});
});
console.log('Server listening on 33333..');
netServer.listen(33333);
}
var newDataCallback = null;
function setNewDataCallback(callback) {
newDataCallback = callback;
}
module.exports = {
sendData: sendData,
startServer: startServer,
setNewDataCallback: setNewDataCallback
};
main.js
var server = require('./server');
function newDataCallback(data) {
console.log('newDataCallback: New data from server: ', data);
}
server.setNewDataCallback(newDataCallback);
server.startServer();
function wheneverUserClicksButton() {
server.sendData('something');
}
testClient.js
var clientSocket = net.createConnection(33333, "127.0.0.1");
clientSocket.on('data', (someData) => {
console.log('Data received', someData);
});
clientSocket.on('connect', () => {
console.log('Client Socket connected ');
clientSocket.write('Hello from client');
});

NodeJs net.Socket() events not firing

Trying to write a TCP client in Node v0.10.15 and I am having a little trouble getting data back from the server. I know that the server is working properly because I have 3-4 different clients written in different languages communicating with it.
Below is a snippet of a larger piece of code but this should get the point across.
The problem is: I'm expecting 2 packets coming back after writing to the socket (this part is not included in this example). I'm only seeing the "data" event being fired once. Is there something that I need to do to get node to resume reading from the Tcp stream? I can confirm that the server is sending 2 packets(The length and then the actual data) Any help would be appreciated.
var dc = require('./DataContracts.js');
var net = require('net');
require('buffertools').extend();
var client = net.Socket();
var isConnected = false;
var serverHost = '10.2.2.21';
var dataCallback;
var receivedBuffer = new Array();
function InitComm(buffer) {
if (!isConnected) {
client.connect(4987, serverHost, function() {
client.on('data', function(data) {
console.log('Received server packet...');
var buf = new Buffer(data);
receivedBuffer.push(buf);
client.resume();
});
client.on('end', function() {
if (receivedBuffer.length > 1) {
if (dataCallback !== undefined)
dataCallback(receivedBuffer);
}
});
client.on('close', function() {
//clean up
});
client.on('error', function(err) {
console.log('Error!: ' + err);
});
Communicate(buffer);
});
} else {
Communicate(buffer);
}
}
Turns out that node was combining both of the packets together. I must be missing a Carriage return on the first packet

Node.js net events don't fire

I have the following example of listening to connection and data events, to echo the result back to other telnet clients listening on port 8888. My telnet sessions connect to locahost fine, but no output is echoed. I am hitting my head against a brick wall trying to figure out what is wrong. The execution doesn't even get as far as the 'connect' event.
/server.js
var events = require('events');
var net = require('net');
var channel = new events.EventEmitter();
channel.clients = {};
channel.subscriptions = {};
channel.on('join', function (id, client) {
this.clients[id] = client;
this.subscriptions[id] = function (senderId, message) {
if (id != senderId) {
this.clients[id].write(message);
}
}
this.on('broadcast', this.subscriptions[id]);
});
var server = net.createServer(function (client) {
var id = client.remoteAddress + ':' + client.remotePort;
console.log(id);
client.on('connect', function () {
console.log('A new connection was made');
channel.emit('join', id, client);
});
client.on('data', function (data) {
data = data.toString();
channel.emit('broadcast', id, data);
});
});
server.listen(8888);
I then run in the command line
node server.js
telnet 127.0.0.1 8888
When the callback to net.createServer is called, that's because of an implicit connection event. So your code should look like this:
var server = net.createServer(function (client) {
// when this code is run, the connection has been established
var id = client.remoteAddress + ':' + client.remotePort;
console.log('A new connection was made:', id);
channel.emit('join', id, client);
client.on('data', function(data) {
...
});
client.on('end', function() {
...
});
});
The manual has this to say;
net.createServer([options], [connectionListener])
Creates a new TCP server. The connectionListener argument is automatically set as a listener for the 'connection' event.
In other words, your function (client) { already received the connection event, and adding a listener to it when it has already been dispatched has no further effect.

How will Node.JS process loop control while there's async function called in the loop?

My situation is as follows: there's an array of IP address. I will test each IP to connect to a remote server. If one IP connects, the rest IPs are ignored and not going to be connected.
I used the following Node.JS codes to do the work, but it seems not working. Please give some hints. Thanks!
// serverip is a var of string splitted by ";", e.g. "ip1;ip2;ip3"
var aryServerIP = serverip.split(";");
console.log(aryServerIP);
var ipcnt = aryServerIP.length; // ipcnt = 3, for example
for (ip in aryServerIP)
{
console.log("to process: " + ipcnt); // error here: always print 3
var net = require('net');
var client = new net.Socket();
var rdpport = 3389;
client.connect(rdpport, aryServerIP[ip], function(){
console.log("socket connected to " + aryServerIP[ip] + ":" + rdpport);
client.destroy();
if (0 != ipcnt)
{
// do some real connection work about aryServerIP[ip].
ipcnt--;
}
});
client.on('error', function(){
console.log("fail to connect to " + aryServerIP[ip] + ":" + rdpport);
ipcnt--;
});
}
I know using ipcnt count to control the loop is bad, but I don't know how to control the Node.JS loop, when there's async function called in the loop...
Because your connect and error callbacks are both asynchronous, so they will both run after the for loop has completely finished.
What you need to do is set up a set of callbacks. For instance, rather than use a for loop, wrap your entire loop body in a function. If connect succeeds, then just do what you normally would, and if the error callback is called, then execute the wrapping function again. Something like this:
var async = require('async');
var net = require('net');
var rdpport = 3389;
function tryConnections(aryServerIP, callback){
function connect(i){
if (i === aryServerIP.length) return callback();
var client = new net.Socket();
client.connect(rdpport, aryServerIP[i], function(){
callback(client);
});
client.on('error', function(){
connect(i + 1)
});
}
connect(0)
}
tryConnections(serverip.split(";"), function(client){
if (client) // Successfully connected to something
else // all ips failed
});
Another solution would be to use the Async library.
function tryConnections(aryServerIP, callback){
async.detectSeries(aryServerIP, function(ip, cb){
var client = new net.Socket();
client.connect(rdpport, ip, function(){
cb(client);
});
client.on('error', function(){
cb();
});
}, callback);
}

How to create a named pipe in node.js?

How to create a named pipe in node.js?
P.S.:
For now I'm creating a named pipe as follows. But I think this is not best way
var mkfifoProcess = spawn('mkfifo', [fifoFilePath]);
mkfifoProcess.on('exit', function (code) {
if (code == 0) {
console.log('fifo created: ' + fifoFilePath);
} else {
console.log('fail to create fifo with code: ' + code);
}
});
Working with named pipes on Windows
Node v0.12.4
var net = require('net');
var PIPE_NAME = "mypipe";
var PIPE_PATH = "\\\\.\\pipe\\" + PIPE_NAME;
var L = console.log;
var server = net.createServer(function(stream) {
L('Server: on connection')
stream.on('data', function(c) {
L('Server: on data:', c.toString());
});
stream.on('end', function() {
L('Server: on end')
server.close();
});
stream.write('Take it easy!');
});
server.on('close',function(){
L('Server: on close');
})
server.listen(PIPE_PATH,function(){
L('Server: on listening');
})
// == Client part == //
var client = net.connect(PIPE_PATH, function() {
L('Client: on connection');
})
client.on('data', function(data) {
L('Client: on data:', data.toString());
client.end('Thanks!');
});
client.on('end', function() {
L('Client: on end');
})
Output:
Server: on listening
Client: on connection
Server: on connection
Client: on data: Take it easy!
Server: on data: Thanks!
Client: on end
Server: on end
Server: on close
Note about pipe names:
C/C++ / Nodejs: \\.\pipe\PIPENAME CreateNamedPipe
.Net / Powershell: \\.\PIPENAME NamedPipeClientStream / NamedPipeServerStream
Both will use file handle: \Device\NamedPipe\PIPENAME
Looks like name pipes aren't and won't be supported in Node core - from Ben Noordhuis 10/11/11:
Windows has a concept of named pipes but since you mention mkfifo I
assume you mean UNIX FIFOs.
We don't support them and probably never will (FIFOs in non-blocking
mode have the potential to deadlock the event loop) but you can use
UNIX sockets if you need similar functionality.
https://groups.google.com/d/msg/nodejs/9TvDwCWaB5c/udQPigFvmgAJ
Named pipes and sockets are very similar however, the net module implements local sockets by specifying a path as opposed to a host and port:
http://nodejs.org/api/net.html#net_server_listen_path_callback
http://nodejs.org/api/net.html#net_net_connect_path_connectlistener
Example:
var net = require('net');
var server = net.createServer(function(stream) {
stream.on('data', function(c) {
console.log('data:', c.toString());
});
stream.on('end', function() {
server.close();
});
});
server.listen('/tmp/test.sock');
var stream = net.connect('/tmp/test.sock');
stream.write('hello');
stream.end();
Maybe use fs.watchFile instead of named pipe ? See documentation

Resources