javascript - Cum să creezi un client TCP în NodeJS folosind async/await?


Am scris următorul client tcp în nodejs.

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);

Vă rog să sugerați cum pot să scriu aceeași logică folosind async/await

Am consultat următoarea postare, dar nu este utilă. Probleme cu node 7.6 async await la returnarea datelor

Răspuns #1

Există un pachet uimitor care înfășoară socket-ul nativ Node într-o promisiune. Permițându-vă să utilizați sintaxa async/await pentru toate metodele socket-ului.

Pachetul poate fi găsit pe NPM.

Exemplu

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"})