3

为什么不保证交付您请求send()winsock所有字节?

这是 TCP,它正在阻塞套接字。

同样,在非阻塞时也会发生这种情况。你怎么能保证你发送的一切?

我注意到recv()做同样的事情。

4

3 回答 3

7

If it didn't send everything, just call send again on the rest. If blocking, you can do it immediately. If non-blocking, you can either wait or use a socket discovery method (like select or I/O completion ports). The same goes for recv. If you didn't get all you wanted, call recv again. This is one of the reasons both recv and send return the number of bytes sent or received.

The number of bytes you pass to send or recv is just a limit. It can send less than that (though, unless non-blocking, usually won't). But it can definitely receive less than that. (The OS has no control over how much data it receives or when it receives it.)

TCP is implemented for you. But if you have an application protocol that involves application-level messages, then the application has to implement them. It won't happen by magic. TCP doesn't "glue the bytes together" into a message for you. TCP is a byte-stream protocol, not a message protocol. If you want messages, you have to implement them.

于 2013-01-18T13:11:03.810 回答
5

这种行为是“设计使然”。

您可以使用外部循环,如本例所示:

int sendBuffer (SOCKET ClientSocket, const char *buf, int len, int flags) 
  {
    int num_left = len;
    int num_sent;
    int err = 0;
    const char *cp = buf;

    while (num_left > 0) 
      {
        num_sent = send(ClientSocket, cp, num_left, flags);

        if (num_sent < 0) 
          {
            err = SOCKET_ERROR;
            break;
          }

        assert(num_sent <= num_left);

        num_left -= num_sent;
        cp += num_sent;
      }

    return (err == SOCKET_ERROR ?  SOCKET_ERROR : len);
  }
于 2013-01-18T13:17:59.730 回答
0

send tells you what it was able to send via its return value. Loop until send has cumulatively sent all the data or returns an error.

于 2013-01-18T13:13:03.763 回答