C - 填充 TCP 套接字发送缓冲区

标签 c sockets tcp buffer select-function

我正在尝试编写一个实验性的客户端/服务器程序来证明当发送缓冲区已满时写入是否失败或阻塞。 基本上,我在发送程序上有一个无限循环,我使用 select() 检查我是否可以在缓冲区上写入(我认为这意味着套接字缓冲区未满),如果我可以在缓冲区上写入比我写()一个字符。当 FD_ISSET(sockfd, &writefds) 为 false 时,循环中断(我无法写入缓冲区,因为它已满)。 接收程序在开始 read() 之前休眠一分钟。我希望发送者在此休眠时间内填充缓冲区,但事实上,程序永远不会结束。

发件人:

int main(int argc, char *argv[]) {
    char buffer[100];
    int sockfd, total = 0, bytes = 0;
    fd_set writefds;

    sockfd = dial(argv[1], argv[2]);
    bzero(buffer, sizeof buffer);

    while(1)
    {
        int ret = 0;
        FD_ZERO(&writefds);
        FD_SET(sockfd, &writefds);

        if((ret = select(sockfd + 1, NULL, &writefds, NULL, 0)) < 0)
        {
            perror("select");
            exit(errno);
        }

        if(FD_ISSET(sockfd, &writefds))
        {
            write(sockfd, "a", 1);
            total++;
            continue;
        }
        else
        {
            puts("I can't write in the socket buffer");
            break;
        }
    }
    printf("nb chars written: %d\n", total);

    return 0;
}

接收者:

int foo(int sockfd) {
    char buffer[100];
    int t, total = 0;

    bzero(buffer, sizeof buffer);
    printf("I have a new client\n");

    sleep(60);

    while((t = read(sockfd, buffer, sizeof buffer)) > 0)
    {
        total += t;
        printf("%d ", total);
    }
    printf("nb chars read: %d\n", total);

    if(t < 0)
    {
        perror("read");
    }

    printf("I don't have that client anymore\n");
    return 0;
}

最佳答案

您的选择超时为空,因此 select() 将在发送缓冲区已满时阻塞。这意味着当它返回时,套接字是可写的,您永远不会得到您的代码“我不能在套接字缓冲区中写入”。

参见手册页 http://linux.die.net/man/2/select

如果您想要零超时,即不要在 select() 上阻塞,您需要将指针传递给两个字段都设置为零的 timeval 结构。

关于C - 填充 TCP 套接字发送缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22761035/

相关文章:

c - 在C中设置TCP重传超时

c - 为什么temp指针指向0而不是3?

java - 如何确保我的 HttpClient 4.1 不泄漏套接字?

objdump 和 gdb 的组合

c - 我如何使用仅使用 C 标准库的套接字连接?

java - 如何在java中获取UDP数据包发送者的本地IP地址

sockets - Netty 服务器如何知道客户端何时断开连接?

python - 使用 python 在 Elastic-beanstalk 中部署 TCP 服务器

c - 调用 enif_free() 时出现段错误

c - 检测静态库是否为瘦存档