C socket: recv and send all data

后端 未结 3 1914
悲&欢浪女
悲&欢浪女 2020-12-14 12:11

I would like to obtain a behavior similar to this:

  1. Server run
  2. Client run
  3. Client type a command like \"help\" or other
  4. Server respond
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 12:24

    The recv() and send() functions do not guarantee to send/recv all data (see man recv, man send)

    You need to implement your own send_all() and recv_all(), something like

    bool send_all(int socket, void *buffer, size_t length)
    {
        char *ptr = (char*) buffer;
        while (length > 0)
        {
            int i = send(socket, ptr, length);
            if (i < 1) return false;
            ptr += i;
            length -= i;
        }
        return true;
    }
    

    The following guide may help you Beej's Guide to Network Programming

提交回复
热议问题