Search code examples
csocketswebsockettcp

How to receive CHUNK's of data from recv() in BSD Sockets in C programming?


I have implemented a websocket client library in C using socket. It was working properly with many websocket servers. But when I try to connect with one of my customer server, the websocket message was comes in many chunks of data. For all other servers, when I use recv() it will receive one whole websocket frame completely but this particular server will send that one websocket frame in 2 TCP packets so I have to again use recv() to get the remaining websocket frame. Then I tried to check this server with some websocket client tools and it was working fine. I need to know the logic, to implement the recv() for this and how to concatenate and figure when the websocket frame was completely received to parse the data? Somebody help me with this please.

while(1){
  ws_recv_ret = recv(*ws_sock, ws_recv, 1024, 0);
  ws_parser_execute(&ws_frame_parser1, ws_recv);
}

Solution

  • I have used MSG_DONTWAIT flag in recv and run it in a loop and append new data to the buffer. After that the recv throws -1 with errno EAGAIN then I break the loop and parse the websocket data. And thanks @user253751 for the explanation, it helps to clear some doubt which arose in my mind about the implementation. The below is the code snippet I used in my library.

    ws_recv_totalSize = 0;
    ws_recv_ret = 0;
    while(1){
      ws_recv_totalSize += ws_recv_ret;
      ws_recv_ret = recv(*ws_sock, ws_recv + ws_recv_totalSize, MAX_BUFFER- ws_recv_totalSize, MSG_DONTWAIT);
          
      if(ws_recv_ret <= 0)
        break;
    }