I'm implementing a server that receives a stream of bytes from the client.
The stream is serialized using msgpack, (and the first thing that is serialized is the length of the remaining stream).
My question is, What's the correct way of receiving this stream in C?
In python I can do this as follows:
# Feed each byte into the Unpacker
unpacker.feed(client.recv(1))
# Unpack whatever we can from the bytes we have received
for value in unpacker:
print(value)
Is there a way I can do this in C?
I solved it, all I had to do is the following:
msgpack_unpacker tUnpacker = { 0 };
BOOL bUnpacked = FALSE;
unsigned char abReceivedBytes[1] = { 0 };
msgpack_unpacked tUnpacked = { 0 };
msgpack_unpack_return eUnpackRet = MSGPACK_UNPACK_PARSE_ERROR;
while (FALSE == bUnpacked)
{
// Read here from socket
...
/* Check buffer capacity and reserve more buffer if needed */
if (msgpack_unpacker_buffer_capacity(&tUnpacker) < nNumOfBytes)
{
bResult = msgpack_unpacker_reserve_buffer(&tUnpacker, nNumOfBytes);
if (FALSE == bResult)
{
// Handle error
}
}
/* feeds the buffer. */
memcpy(msgpack_unpacker_buffer(&tUnpacker), &abReceivedBytes[0], nNumOfBytes);
msgpack_unpacker_buffer_consumed(&tUnpacker, nNumOfBytes);
/* initialize the unpacked message structure */
msgpack_unpacked_init(&tUnpacked);
eUnpackRet = msgpack_unpacker_next(&tUnpacker, &tUnpacked);
switch (eUnpackRet) {
case MSGPACK_UNPACK_SUCCESS:
/* Extract msgpack_object and use it. */
bUnpacked = TRUE;
break;
case MSGPACK_UNPACK_CONTINUE:
break;
default:
// Handle failure
...
}
This is how you can read a stream using msgpack (This is almost equivalent to the python script in my question)