0
votes

I tried to learn about the conception of Socket-Send(Receive)-Buffer.And I wrote these codes: Client:

int client = socket(AF_INET, SOCK_STREAM, 0);
int s = getsockopt(client, SOL_SOCKET, SO_SNDBUF, &sendBuffSize, &len);
int status = connect(client, (struct sockaddr*)&addr, sizeof(struct sockaddr_in));
printf("The send buff size is : %d.\n", sendBuffSize);
char buf[100000];
int n, wn;
int fd = open("./1.txt", O_RDONLY);
while ((n = read(fd, buf, sizeof(buf))) > 0) {
    wn = write(client, buf, n);
    printf("Write %d bytes.\n", wn);
}

Server: I set the connected client as Non-block,and add this client into the epoll.Once the client sends data to the server, I put the main thread into sleep[ten seconds].

char buf[8192];
sleep(10);
int rn;
while ((rn = read(events[i].data.fd, buf, sizeof(buf))) > 0) {
    printf("Read %d bytes.\n", rn);
}

The client send Buffer size is 16384 and the server receive Buffer size is 20000[setsockopt].

According to the book:The client calls the write function will block if the socket send buffer is full.

But I get the result[Client] : Result

And the server : Result

Questions:

  1. Receive buffer size + Send buffer size < 100000; but why the write function do not block?
  2. Why the server read 8192 + 6808 = 15000 bytes instead of read continuously 8192 bytes?
1
Is this a curiosity thing or are you trying to design a program that actually relies on the size of the buffers? - user253751
Thank you for response.I am a beginner. I just want to understand the conception of socket buffer, so I wrote this program to checkout whether I really understand it.But the result makes me confused. - Greetlist
I think Linux includes some overhead per packet in the socket buffer size. For most programming you need to know that there's a socket buffer, but the exact size etc. is unreliable. - user253751
Thank you,I will keep this in mind. - Greetlist

1 Answers

1
votes
  1. There is no evidence here that the client writes did not block. On the contrary, the fact that all the writes were 100,000 bytes except the last, when you ran out of input, shows that it must have blocked, to transfer all that data into a socket buffer that is smaller.

  2. TCP segmentizes, and IP packetises, the data sent over the wire. You have no control over that process. In any case a read() can transfer any amount of bytes from 1 up to the count supplied, or zero upwards in non-blocking mode. It is a streaming protocol, not a messaging protocol. There is no other guarantee about how much any individual read() will return at a time.