C++ TCP网络编程详细讲解

  #include

  #include //socket

  #include //struct sockaddr_in

  #include //memset

  #include //htos

  #include //close

  int main()

  {

  //创建套接字

  int sockfd = socket(AF_INET, SOCK_DGRAM, 0);

  if(sockfd < 0)

  {

  perror("cockt");

  return 0;

  }

  //bind绑定固定的port、ip地址信息

  struct sockaddr_in my_addr;

  bzero(&my_addr, sizeof(my_addr));

  my_addr.sin_family = AF_INET;

  my_addr.sin_port = htons(9000);

  my_addr.sin_addr.s_addr = htonl(INADDR_ANY);

  int ret = bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr));

  if(ret == -1)

  {

  perror("bind");

  return 0;

  }

  //监听套接字 创捷连接队列

  ret = listen(sockfd, 10);

  if(ret == -1)

  {

  perror("listen");

  return 0;

  }

  //提取客户端的连接

  while(1)

  {

  //一次只能提取一个客户端

  struct sockaddr_in cli_addr;

  socklen_t cli_len = sizeof(cli_addr);

  int cfd = accept(sockfd, (struct sockaddr *)&cli_addr, &cli_len);

  if(cfd < 0 ) //提取失败

  {

  perrer("accept

  ");

  break;

  }

  else

  {

  char ip[16] = "";

  unsigned short port = 0;

  inet_ntop(AF_INET, &cli_addr.sin_addr.s_addr, ip, 16);

  port = ntohs(cli_addr.sin_port);

  //打印客户端的信息

  printf("客户端:%s %d connected

  ", ip, port);

  while(1)

  {

  //获取客户端的请求

  unsigned char buf[1500] = "";

  int len = recv(cfd, buf, sizeof(buf), 0);

  if(len == 0) //客户端已经关闭

  {

  //关闭与客户端连接的套接字

  close(cfd);

  break;

  }

  //应答客户端

  send(cfd, buf, len, 0);

  }

  }

  }

  //关闭监听套接字

  close(sockfd);

  return 0;

  }