I have tcp client, that reads data from socket and copies it to circular_buffer. Then it reads packets from that buffer and should process them async.
boost::asio::thread_pool pool{3};
boost::circular_buffer<u_char> buffer;
class Packet {
public:
bytes Data{ 0,0 };
byte* Reader;
Packet() { Data.reserve(4096); }
Packet(byte* data, size_t len) {
Data.reserve(4096);
Data.assign(&data[0], &data[len]);
Reader = &Data[0];
}
};
void NetClient::Receive(u_char* data, size_t size) {
std::copy(&data[0], &data[size], std::back_inserter(buffer));
size_t i = 0;
ushort packetLength = 0;
size_t len = buffer.size();
while (i < len)
{
if (i + 1 >= len)
{
break;
}
packetLength = buffer[i] + (buffer[i + 1] << 8);
if (i + packetLength > len)
{
break;
}
std::vector<byte> tmp;
tmp.reserve(packetLength - 2);
tmp.assign(&buffer[i + 2], &buffer[i + packetLength]);
boost::asio::post(pool, [this, tmp]{
Packet packet((u_char*)tmp.data(), tmp.size());
ProcessPacket(packet);
});
i += packetLength;
}
buffer.erase_begin(i);
}
I've tried to create Packet outside lambda then capture packet but this way it doesn't have data, only size.
What it the right way to pass data vector as packet to a different thread? How can I avoid so much coping?
This code works but sometimes I receive an error "transposed pointer range" on line boost::asio::post(pool, [this, tmp]{ what is this? Why is this happenenig?