首页 > 代码库 > 《UNP》习题1.5源码

《UNP》习题1.5源码

首先是服务器程序:

#include <unp.h>
#include <time.h>

int main()
{
    int listenfd, connfd;
    int nWrite;
    int count;
    struct sockaddr_in servaddr;
    char buff[MAXLINE];
    time_t ticks;

    listenfd = Socket( AF_INET, SOCK_STREAM, 0 );

    bzero( &servaddr, sizeof(servaddr) );
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl( INADDR_ANY );
    servaddr.sin_port = htons( 9999 );

    Bind( listenfd, (SA *)&servaddr, sizeof(servaddr) );

    Listen( listenfd, LISTENQ );

    for(;;) {
        connfd = Accept( listenfd, (SA *)NULL, NULL );

        ticks = time(NULL);
        snprintf( buff, sizeof(buff), "%.24s\r\n", ctime(&ticks) );
        nWrite = strlen(buff);
        for( count=0; count<nWrite; count++ ) 
            Write( connfd, buff+count, 1 );

        Close( connfd );
    }
    exit(0);
}

然后是客户端程序:

#include <unp.h>

int main(int argc, char **argv)
{
    int sockfd, n;
    int count = 0;
    char recvline[MAXLINE+1];
    struct sockaddr_in servaddr;

    if( 2 != argc )
        err_quit("usage: a.out <IPaddress> ");

    if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
        err_sys("socket error");

    bzero( &servaddr, sizeof(servaddr) );
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(9999);
    if( inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0 )
        err_quit("inet_pton error for %s", argv[1]);

    if( connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0 )
        err_sys("connect error");

    while( (n = read( sockfd, recvline, MAXLINE )) > 0 ) {
        recvline[n] = 0;
        count++;
        if( fputs(recvline, stdout) == EOF )
            err_sys("fputs error");
    }

    if( n<0 )
        err_sys("read error");
    printf("read times: %d\n", count);
    exit(0);
}

程序运行结果:

[zhang@localhost UNP]$ ./daytimesrv & ./daytimecli 127.0.0.1
[1] 6126
Thu Jan 15 19:52:21 2015
read times: 1

程序结果说明:

如果客户和服务器运行在同一个主机上,那么计数器的值通常是1,意味着尽管服务器调用了26次write,所写出的数据也仅由客户的一次read返回。

《UNP》习题1.5源码