【问题标题】:How to create TCP client in NodeJS using async/await?如何使用 async/await 在 NodeJS 中创建 TCP 客户端?
【发布时间】:2020-02-05 23:17:32
【问题描述】:

我在nodejs中写了以下tcp client

const net = require('net');

const HOST = 'linux345';
const PORT = 2345;
let ErrCode = 1;

const client = new net.Socket();

client.connect(PORT, HOST, function() {
    ErrCode = 0;
});

client.on('data', function(data) {    
    console.log('Client received: ' + data);
     if (data.toString().endsWith('exit')) {
       client.destroy();
    }
});

client.on('close', function() {
});

client.on('error', function(err) {
    ErrCode = err.code;
    console.log(ErrCode);
});

console.log(ErrCode);

请建议我如何使用 async/await 编写相同的逻辑

我查看了以下帖子,但没有帮助。 node 7.6 async await issues with returning data

【问题讨论】:

标签: javascript node.js angular promise async-await


【解决方案1】:

有一个神奇的包将原生 Node 套接字包装在一个 Promise 中。允许您在所有套接字方法上使用async/await 语法。

包可以在NPM找到。

示例

import net from "net"
import PromiseSocket from "promise-socket"

const socket = new net.Socket()

const promiseSocket = new PromiseSocket(socket)

await connect(80, "localhost")
// or
await connect({port: 80, host: "localhost"})

【讨论】:

    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 2018-06-13
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 2020-08-07
    • 2010-09-20
    相关资源
    最近更新 更多