server

int main(void)
{
 struct sockaddr_in servaddr, cliaddr;
 socklen_t cliaddr_len;
 int listenfd, connfd;
 char buf[MAXLINE];
 char str[INET_ADDRSTRLEN];
 int i, n;
 char header[MAX][MAXLENGTH];
 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(SERV_PORT);

 bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

 listen(listenfd, 20);
//绑定的是监听套接字,而接受返回的套接字是从内核队列得到的已建立连接的套接字,二者完全不同,
 printf("Accepting connections ...\n");
 while (1) {
  cliaddr_len = sizeof(cliaddr);
  connfd = accept(listenfd,
    (struct sockaddr *)&cliaddr, &cliaddr_len);
  int pid = fork();
  if (pid == 0) {
   while (1) {
    n = read(connfd, buf, MAXLINE);
    if (n == 0) {
     printf("the other side has been closed.\n");
     break;
    }
    printf("received from %s at PORT %d\n",
     inet_ntop(AF_INET, &cliaddr.sin_addr, str, sizeof(str)),
     ntohs(cliaddr.sin_port));

    /*for (i = 0; i < n; i++)
     buf[i] = toupper(buf[i]);
    write(connfd, buf, n);*/
                            parse(buf,strlen(buf),header);
                                      if(resp(header)==1)
                                        printf("OK");
   }
   close(connfd);  //接受完数据就会关闭socket
   exit(0);
  } else if(pid > 0)
  //connfd 在fork()之后connfd 被复制,文件唯一关联的打开描叙符在父子进程打开1次。
  //共2次,close(connfd) 减1 ,打开描叙符为0时才是真正关闭。
   close(connfd);
 }
}

你可能感兴趣的:(server)