简体   繁体   English

套接字发送和接收缓冲区

[英]Socket Send And Receive Buffer

I tried to learn about the conception of Socket-Send(Receive)-Buffer.And I wrote these codes: Client: 我试图了解Socket-Send(Receive)-Buffer的概念,并编写了以下代码: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]. 服务器:我将连接的客户端设置为Non-block ,并将此客户端添加到epoll中。一旦客户端将数据发送到服务器,我就将主线程置于sleep [十秒钟]。

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]. 客户端发送缓冲区大小为16384,服务器接收缓冲区大小为20000 [setsockopt]。

According to the book:The client calls the write function will block if the socket send buffer is full. 根据书中所述:如果套接字发送缓冲区已满,则客户端调用write函数将阻塞。

But I get the result[Client] : Result 但是我得到了结果[客户]: 结果

And the server : Result 和服务器: 结果

Questions: 问题:

  1. Receive buffer size + Send buffer size < 100000; 接收缓冲区大小+发送缓冲区大小<100000; but why the write function do not block? 但是为什么写功能没有阻塞?
  2. Why the server read 8192 + 6808 = 15000 bytes instead of read continuously 8192 bytes? 为什么服务器读取8192 + 6808 = 15000字节而不是连续读取8192字节?
  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. 相反,除了最后一次写入时,所有写入均为100,000个字节(当您的输入用完时)表明,它必须已被阻塞,才能将所有数据传输到较小的套接字缓冲区中。

  2. TCP segmentizes, and IP packetises, the data sent over the wire. TCP对通过网络发送的数据进行分段,并对IP进行打包。 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. 在任何情况下, read()都可以从1到提供的计数之间传输任意数量的字节,或者在非阻塞模式下向上传输零。 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. 关于任何单个read()一次返回多少没有其他保证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM