TCP打开文件传输(服务器端并发code)

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <unistd.h>

#define MAXLINE 4096

void str_echo(int sockfd) {
  ssize_t n;
  char buff[MAXLINE];

  printf("----echo----\n");
  while((n = read(sockfd, buff, MAXLINE)) > 0) {
    if(write(sockfd, buff, strlen(buff)) != strlen(buff)) {
      printf("write error\n");
      exit(-1);
    }
  }
}

int main() {
  int listenfd, connfd;
  socklen_t clilen;
  pid_t pid;
  struct sockaddr_in servaddr, cliaddr;
  char buff[MAXLINE];

  listenfd = socket(AF_INET, SOCK_STREAM, 0);
  if(listenfd < 0) {
    printf("socket error\n");
    exit(-1);
  }

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

  if(bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
    printf("bind error");
    exit(-1);
  }

  if(listen(listenfd, 1024) < 0) {
    printf("listen error");
    exit(-1);
  }
  printf("----server is listening----\n");

  for(;;) {
    clilen = sizeof(cliaddr);

    if((connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen)) < 0) {
      printf("accept error");
      exit(-1);
    }

    printf("ip: %s, port: %d\n", inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)), ntohs(cliaddr.sin_port));
    printf("----------connected-------\n");

    if((pid = fork()) < 0) {
      printf("fork error\n");
      exit(-1);
    }
    else if(pid == 0) { /* child */
      printf("---child pid = %ld process---\n", (long)getpid());
      if(close(listenfd) < 0) {
        printf("---child close listenfd error---\n");
        exit(-1);
      }
      str_echo(connfd);
      if(close(connfd) < 0) {
        printf("---child close connfd error---\n");
        exit(-1);
      }
      exit(0);
    }
    else { /* parent */
      if(close(connfd) < 0) {
        printf("---parent close connfd error---\n");
        exit(-1);
      }
    }
  }
  exit(0);
}

从这些代码中可以体会到客户/服务器网络应用所需的所有基本步骤。

posted @ 2018-03-31 14:48  东宫得臣  阅读(192)  评论(0编辑  收藏  举报