Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用async/await在NodeJS中创建TCP客户端?_Javascript_Node.js_Angular_Promise_Async Await - Fatal编程技术网

Javascript 如何使用async/await在NodeJS中创建TCP客户端?

Javascript 如何使用async/await在NodeJS中创建TCP客户端?,javascript,node.js,angular,promise,async-await,Javascript,Node.js,Angular,Promise,Async Await,我已经在nodejs中编写了以下tcp客户机 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) {

我已经在nodejs中编写了以下
tcp客户机

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编写相同的逻辑

我已经研究了下面的帖子,但没有帮助。
有一个惊人的包,它将本机节点套接字封装在promise中。允许您在所有套接字方法上使用
async/await
语法

该软件包可在上找到

示例

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"})
这可能会帮助您: