Unix Network Programming Episode 48

博客主要围绕‘str_cli’函数展开,介绍了处理套接字的三种情况,包括对等TCP发送数据、FIN和RST时的不同表现,还提及使用select实现该函数。同时指出当前str_cli函数存在问题,其原版本采用停等模式,适用于交互使用,可根据客户端与服务器间的RTT估算响应时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

‘str_cli’ Function (Revisited)

Three conditions are handled with the socket:

1.If the peer TCP sends data, the socket becomes readable and read returns greater than 0 (i.e., the number of bytes of data).
2.If the peer TCP sends a FIN (the peer process terminates), the socket becomes readable and read returns 0 (EOF).
3.If the peer TCP sends an RST (the peer host has crashed and rebooted), the socket becomes readable, read returns –1, and errno contains the specific error code.

#include "unp.h"

void str_cli(FILE *fp, int sockfd)
{
    int maxfdp1;
    fd_set rset;
    char sendline[MAXLINE], recvline[MAXLINE];

    FD_ZERO(&rset);

    for(;;)
    {
        FD_SET(fileno(fp), &rset);
        FD_SET(sockfd, &rset);
        maxfdp1=max(fileno(fp), sockfd)+1;
        Select(maxfdp1, &rset, NULL, NULL, NULL);

        if(FD_ISSET(sockfd, &rset))
        {
            if(Readline(sockfd, recvline, MAXLINE)==0)
                err_quit("str_cli: server terminated prematurely");
            Fputs(recvline, stdout);
        }

        if(FD_ISSET(fileno(fp), &rset))
        {
            if(Fgets(sendline, MAXLINE, fp)==NULL)
                return;
            Writen(sockfd,sendline, strlen(sendline));
        }
    }
}

Implementation of str_cli function using select (improved in Figure 6.13(See 8.4.7)).

Batch Input and Buffering

Unfortunately, our str_cli function is still not correct. First, let’s go back to our original version, Figure 5.5(See 8.3.5). It operates in a stop-and-wait mode, which is fine for interactive use: It sends a line to the server and then waits for the reply. This amount of time is one RTT plus the server’s processing time (which is close to 0 for a simple echo server). We can therefore estimate how long it will take for a given number of lines to be echoed if we know the RTT between the client and server.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值