javascript - NodeJS getting response from net socket write - Stack Overflow

I'm trying to get a response from specific requests via the write function.I'm connected to a

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.

Share Improve this question edited Nov 17, 2017 at 21:48 Eyzi asked Nov 17, 2017 at 21:34 EyziEyzi 5161 gold badge6 silver badges20 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Add 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信