I’m sure some of you have already tackled this problem, and if so, feel free to shake your heads and write this off as n00btacular. I’m just curious how quickly anyone can devise a solution.
This problem is pretty specific, “let n be an integer” style. Here goes:
You’re writing a networked program in C, specifically using TCP. You’re going to receive some data from the server, but you’re not sure how much information there will be. Your only indicator will be, somewhere in the first hundred bytes or so, a “Length” field and a “rnrn” to delineate the end of the header and the start of the body, which will be Length characters long.
If you said “HOLY CARP IT’S HTTP!!1”, you’d be correct, monsieur.
But here’s the problem. You don’t know the size of the header section of the incoming data (some headers could be missing, as many HTTP headers are optional), and you certainly won’t know the size of the incoming body until you find the Length field somewhere in the header and the subsequent “rnrn.”
There is a function, “recv()”, which receives a block of data over a TCP connection of a specified size. But since you have no idea how much information is coming over the wire, you may have to call “recv()” several times before you possess all the data. What would be the best implementation of a function which performs this “recv()” operation several times internally and returns a single reference to the entire block of received data?
The call to this function would look something like this (in pseudo-code):
dataBuffer = receiveAll(socketIdentifier, AnyOtherAdditionalParameters)
It’s certainly not an impossible task. Really, the challenge lies in weighing the pros and cons of each solution, particularly in regards to overall performance and efficiency, and choosing an implementation that solves the problem in the best way possible.
Of course, since C is so finicky about memory, there is also a (rather significant) challenge in making sure all the allocated blocks mesh cleanly, but that lies in the tweaking of the implementation, not the implementation itself.
And by “tweaking” I mean “debugging.” 😛
Oh. And before anyone says anything…yesIknowit’sFridaynightandI’mworking. I’m text messaging/shamelessly flirting with my girlfriend as I program, does that count as a social engagement?