使用回调进行网络异步接收数据时代码可读性差
Bad code readability when using callbacks for network async receiving data
我正在使用我自己的网络库在 C++ 中开发客户端协议。
我创建了从服务器异步接收数据的方法。
接收到数据时回调方法
但是我需要调用嵌套在这个回调中的异步读取数据。
示例:
this->Send(some_data1, some_data_length1);
this->AsyncReceive([some_data2, some_data_length2]() {
this->Send(some_data3, some_data_length3);
this->AsyncReceive([some_data4, some_data_length4]() {
this->Send(some_data5, some_data_length5);
this->AsyncReceive([some_data6, some_data_length6]() {
this->Send(some_data7, some_data_length7);
this->AsyncReceive([some_data8, some_data_length8]() {
this->Send(some_data9, some_data_length9);
// and more..
});
});
});
});
也许有人知道我该如何解决这个问题?
首先,由于这是标记为 C++,因此让您的 API 函数接受广泛的数据范围,而不是指针 + 长度的旧 C 惯用语。
使用户代码可以像下面这样狂放:
std::vector<unsigned char> v;
std::array<unsigned char, 42> a;
std::string str;
std::span<int> s;
// ...
your_api.Send(v);
your_api.Send(a);
your_api.Send(str);
your_api.Send(s);
这将大大提高可用性。然后,向您的 API 添加一个函数,这样用户代码就可以如下所示:
your_api.Send(data);
your_api.AsyncReceiveAndSend([](auto inbound) {
// ...
return outboud;
}).AsyncReceiveAndSend([](auto inbound) {
// ...
return outboud;
}).AsyncReceive([](auto inbound) {
// ...
})
我正在使用我自己的网络库在 C++ 中开发客户端协议。
我创建了从服务器异步接收数据的方法。
接收到数据时回调方法
但是我需要调用嵌套在这个回调中的异步读取数据。
示例:
this->Send(some_data1, some_data_length1);
this->AsyncReceive([some_data2, some_data_length2]() {
this->Send(some_data3, some_data_length3);
this->AsyncReceive([some_data4, some_data_length4]() {
this->Send(some_data5, some_data_length5);
this->AsyncReceive([some_data6, some_data_length6]() {
this->Send(some_data7, some_data_length7);
this->AsyncReceive([some_data8, some_data_length8]() {
this->Send(some_data9, some_data_length9);
// and more..
});
});
});
});
也许有人知道我该如何解决这个问题?
首先,由于这是标记为 C++,因此让您的 API 函数接受广泛的数据范围,而不是指针 + 长度的旧 C 惯用语。 使用户代码可以像下面这样狂放:
std::vector<unsigned char> v;
std::array<unsigned char, 42> a;
std::string str;
std::span<int> s;
// ...
your_api.Send(v);
your_api.Send(a);
your_api.Send(str);
your_api.Send(s);
这将大大提高可用性。然后,向您的 API 添加一个函数,这样用户代码就可以如下所示:
your_api.Send(data);
your_api.AsyncReceiveAndSend([](auto inbound) {
// ...
return outboud;
}).AsyncReceiveAndSend([](auto inbound) {
// ...
return outboud;
}).AsyncReceive([](auto inbound) {
// ...
})