fpagliughi / sockpp

Modern C++ socket library.
BSD 3-Clause "New" or "Revised" License
769 stars 126 forks source link

Receiving Data #64

Closed ryanwe1ss closed 1 year ago

ryanwe1ss commented 2 years ago

Hi, I'm just wondering but is there any mechanism in this repository that can simply be able to receive data from another endpoint without knowing the length of it and be able to receive it all properly? For example, if I send an image on the server side to the client, is there any way I can receive the full image which one simple line to store it all in an array without sending the length of the data first then the actual data?

fpagliughi commented 2 years ago

This library doesn't let you do anything more than what you can do with the standard C socket API. It just wraps it in C++ and makes it a little easier to use.

Assuming that you're talking about a streaming protocol, like TCP, then in general, no, there generally isn't a way to know when you're at the end of a specific run of data other than knowing how many bytes to expect, or putting markers into the stream to frame the data. But using markers with binary data like images is difficult, since the binary data could randomly contain the markers and cause you to lose sync in the stream.

One trick is to just send one item per connection. The sender transmits the image then closes the connection. The receiver then reads all the data till it sees the end of the stream. I've used that technique before, and it works, but introduces a lot of overhead if you want to send a lot of smaller items.

Depending on your requirements, you might want to skip low-level networking libraries like this one and consider a messaging system like RabbitMQ or MQTT. Those do a nice job of chopping up the streams into individual messages, and allow for lots of traffic from different applications. But they generally do require a separate server process (broker) running in the middle.

ryanwe1ss commented 2 years ago

Thanks for the feedback! Definitely, I've been looking for libraries such as this one that simplifies socket use because my goal for using it is to make a somewhat replica of a remote connection tool to interact with remote computers such as sending messages, sending or receiving data (such as image files) and 90% of the time in my project, it seems to work fine but there are times that it is super slow with receiving data, or it just doesn't read the correct length when I send it first, then the actual data that is being read with that length size.