I am working with WebSockets. I created a small test client which splits the message and then sends it chunk by chunk. For example a message like:
PROTOCOL HTTP ACTION UPDATE
could be sent as
PROTOC
as one chunk then
OL HTT
as another as opposed to send the complete message in one chunk as PROTOCOL HTTP ACTION UPDATE
which is also a possibility.
So the way I receive the message must reflect that. Currently, I am not sure how to use recv
when one message will be broken into multiple parts and sent across.
This is what I am trying but I am not sure if this is the correct way. Should I always keep the size of buffer as 200 while receiving? When should I exit the loop?
void recv_all(){
char rec_buffer[200]
while(1) {
ssize_t bytes_rec = recv(socket_fd, rec_buffer, sizeof(rec_buffer),0);
}
}
(stream) sockets deal with byte streams, not messages. So they provide a way of getting a stream of bytes between the endpoints and nothing more. If you want some kind of 'messages' you need to process the byte stream to find the message boudaries and break it up into messages yourself.
The usual way of doing this is with a buffer, such as a C FILE object or a C++ streambuf. You arrange for bytes to be read from the socket into the buffer and then check to see if there's a complete message in the buffer, usually by looking for a message terminator/boundary marker (such as \r\n or just \n). If there is, you remove (just) the message from the buffer.
It's quite easy to do in C with POSIX -- you can use fdopen
to open a FILE with the socket descriptor and then use fgets or getline to read a message up to a newline.