javascript - NodeJS'te async/await kullanarak TCP istemcisi nasıl oluşturulur?
Node.js'te aşağıdaki tcp client'i yazdım.
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);
Aynı mantığı async/await kullanarak nasıl yazabileceğimi lütfen önerin
Aşağıdaki gönderiyi inceledim ama faydalı olmadı. Node 7.6 async await veri döndürme sorunları
Cevap #1
Yerleşik Node soketini bir promise içine saran harika bir paket var. Bu, tüm soket yöntemlerinde async/await sözdizimini kullanmanıza olanak tanır.
Paket NPM üzerinde bulunabilir.
Örnek
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"})
