对一段C语言服务器代码的详解

  • 服务端----其代码如下
#include <stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<unistd.h>
#define SERV_PORT 9898
#define SERV_IP "127.0.0.1"
#include<ctype.h>
#include<arpa/inet.h>
int main()
{

    int lfd,cfd,n,i;
    char buf[BUFSIZ];
    struct sockaddr_in serv_addr,client_addr;
    socklen_t client_addr_len;
    lfd=socket(AF_INET,SOCK_STREAM,0);//
    serv_addr.sin_family=AF_INET;
    serv_addr.sin_port=htons(SERV_PORT);
    serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);//
    bind(lfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
    listen(lfd,128);//128 is uplimit
    client_addr_len=sizeof(client_addr);
    cfd=accept(lfd,(struct client_addr*)&client_addr,&client_addr_len);//will recv fd and return fd
    while(1)
    {
        n=read(cfd,buf,sizeof(buf));
        for(i=0;i<n;i++)
        {
            buf[i]=toupper(buf[i]);
        }
        write(cfd,buf,n);
    }

    printf("Hello World!\n");
    return 0;
}

测试:打开一个终端输入 nc 127.0.0.1 9898

  • 客户端
#include<stdio.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>

#include<sys/socket.h>
#include<string.h>
#define SERV_IP "127.0.0.1"
#define SERV_PORT 9898
int main()
{
    int cfd,n;
    char buf[BUFSIZ];
    struct sockaddr_in serv_addr;
    socklen_t serv_addr_len;
    memset(&serv_addr,0,sizeof(serv_addr));
    cfd=socket(AF_INET,SOCK_STREAM,0);
    serv_addr.sin_family=AF_INET;
    serv_addr.sin_port=SERV_PORT;
    inet_pton(AF_INET,SERV_IP,&serv_addr.sin_addr.s_addr);
    connect(cfd,(struct sockaddr_in *)&serv_addr,sizeof(serv_addr));
    while(1)
    {
        fgets(buf,sizeof(buf),stdin);//gets is out-of-date;use fgets readline until the end, back with \0
        write(cfd,buf,strlen(buf));
        n=read(cfd,buf,sizeof(buf));
        write(STDOUT_FILENO,buf,n);
    }

    close(cfd);
    return 0;
}
posted @ 2019-12-31 12:57  saintdingtheGreat  阅读(319)  评论(0编辑  收藏  举报