I've been tasked with refactoring the below groovy code into Node.js
def sendHubCommand(String hubcmd){
def s = new Socket("IP here", 6767)
s.withStreams { inStream, outStream ->
outStream << hubcmd + "\n"
def reader = inStream.newReader()
def responseText
reader.ready()
responseText = reader.readLine()
//println "response = $responseText"
}
s.close();
return true
}
I've messed around with the below node.js code and had no luck as client.write('nf sensor.contact') doesn't do anything once connected.
var net = require('net');
var client = new net.Socket();
client.connect(6767, 'IP here', function() {
console.log('Connected');
client.write('nf sensor.contact');
});
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');
});
};
}
Essentially I need to open a socket and than be able to send a command to it like was being done in the groovy example but in node.js. Any ideas or help would be appreciated!
I have not used the native net module, but I'm willing to bet it's the new keyword and a bit of your structure.
Try something like this instead:
var net = require('net');
var client = net.connect(6767, 'IP here', function() {
console.log('Connected');
client.write('nf sensor.contact');
});
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');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.