admin 管理员组文章数量: 1086019
I have written the following tcp client
in 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);
Please suggest how can I write same logic using async/await
I have looked into the following post but it is not helpful. node 7.6 async await issues with returning data
I have written the following tcp client
in 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);
Please suggest how can I write same logic using async/await
I have looked into the following post but it is not helpful. node 7.6 async await issues with returning data
Share Improve this question edited Oct 8, 2019 at 16:55 meallhour asked Oct 8, 2019 at 16:13 meallhourmeallhour 15.7k24 gold badges72 silver badges152 bronze badges 1- This might help you: stackoverflow./questions/42440537/… – user11317802 Commented Nov 20, 2019 at 15:23
1 Answer
Reset to default 6There is an amazing package that wraps the native Node socket in a promise. Allowing you to utilize async/await
syntax on all socket methods.
The package can be found on NPM.
Example
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"})
本文标签: javascriptHow to create TCP client in NodeJS using asyncawaitStack Overflow
版权声明:本文标题:javascript - How to create TCP client in NodeJS using asyncawait? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744035065a2522210.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论