I'm trying to get a response from specific requests via the write
function.
I'm connected to an equipment via the net
module (which is the only way to municate with it). Currently, I have an .on('data',function)
to listen to responses from the said equipment. I can send mands via the write
functions to which I am expecting to receive a line of response. How can I go about doing this?
Current code:
server = net.Socket();
// connect to server
server.connect(<port>,<ip>,()=>{
console.log("Connected to server!");
});
// log data ing from the server
server.on("data",(data)=>{
console.log(''+data);
});
// send mand to server
exports.write = function(mand){
server.write(mand+"\r\n");
};
This is a working code. Sending a mand to the equipment via server.write
returns a response which right now only appears in Terminal. I'd like to return that response right after the write
request. Preferably within the exports.write
function.
I'm trying to get a response from specific requests via the write
function.
I'm connected to an equipment via the net
module (which is the only way to municate with it). Currently, I have an .on('data',function)
to listen to responses from the said equipment. I can send mands via the write
functions to which I am expecting to receive a line of response. How can I go about doing this?
Current code:
server = net.Socket();
// connect to server
server.connect(<port>,<ip>,()=>{
console.log("Connected to server!");
});
// log data ing from the server
server.on("data",(data)=>{
console.log(''+data);
});
// send mand to server
exports.write = function(mand){
server.write(mand+"\r\n");
};
This is a working code. Sending a mand to the equipment via server.write
returns a response which right now only appears in Terminal. I'd like to return that response right after the write
request. Preferably within the exports.write
function.
1 Answer
Reset to default 7Add a callback
argument to your exports.write
function can solve your problem.
exports.write = function(mand, callback){
server.write(mand+"\r\n");
server.on('data', function (data) {
//this data is a Buffer object
callback(null, data)
});
server.on('error', function (error) {
callback(error, null)
});
};
call your write
function
var server = require('./serverFilePath')
server.write('callback works', function(error, data){
console.log('Received: ' + data)
})
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744231265a4564262.html
评论列表(0条)