最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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)
})
发布评论

评论列表(0)

  1. 暂无评论