Node.js“ net.createConnection()”错误回调未发出

时间:2019-01-12 16:27:42

标签: javascript node.js sockets

我想连接到Node应用程序中的Unix Domain Socket服务器。如果连接成功并被打开,则将执行一个循环(可能需要一些时间)。如果在执行此循环期间发生错误,则它应该收到某种通知。如果根本无法连接到客户端,则不应首先执行循环(这似乎与Promise一起使用)。对我来说,这听起来像是世界上最简单的事情,但是我无法使其正常工作……这是我到目前为止所拥有的:

  new Promise(function(resolve, reject) {
    let connection = net.createConnection('/tmp/socket.s', () => {resolve(connection);})
      .on('data', function(data) {
        // Do something (during loop execution)
      })
      .on('error', reject); // If this callback is executed, the while loop should terminate (by receiving some kind of signal within the loop)
  }).then(function(connection) {
    for(...) {
      // Do stuff that takes some time, executes other callbacks, sends data to the socket
    }
    connection.end();
  }, function(error) {
    // Error handling
  });

我想念什么?

1 个答案:

答案 0 :(得分:0)

尝试在promise的resolve部分中监听数据事件。下面的代码应该做到这一点:

else if (n<80)

我的测试服务器看起来像这样

const net = require('net');

/**
 * Client
 * --------------------------------------------
 */

new Promise((resolve, reject) => {
    let client = net.createConnection({ path: '/tmp/socket.s'}, () => {
        console.log('Client: connected ')
        resolve(client);
    });

    // Reject on error
    client.on('error', err => reject(err) );

    client.on('end', () => {
        console.log('Client: disconnected from server #1');
    });
}).then( connection => {
    connection.on('data', data => {

        // Do stuff with the data
        console.log(`Client: the server says: ${data.toString()}\n`);

        if(data != 'Data recieved'){
            // Just to ensure that the following loop runs only once
            for (let i = 0; i <= 10; i++) {
                setTimeout(() => {
                    // Send data to the server
                    connection.write(`Client Data ${i}`);
                    if (i == 10) {
                        // Close the connection after everything is done
                        connection.end();
                    }
                }, i*2000);
            }
        }
    });
}, error => {
    console.log('Client: promise rejection error', error );
});

在此示例中,客户端将数据发送到服务器,并且服务器每次都会答复。客户端在发送数据10次后关闭连接。

P.S。除非您确实需要在代码中的某个点返回承诺,否则就不需要使用Promise。