阻塞案例

阻塞案例,由于单线程,同一时间只有一个TCP链接能够被处理。

  1. int main() {
  2. int serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //AF_INT:ipv4, SOCK_STREAM:tcp协议
  3. //将套接字和IP、端口绑定
  4. struct sockaddr_in *serv_addr = malloc(sizeof(struct sockaddr_in));
  5. serv_addr->sin_family = AF_INET; //使用IPv4地址
  6. serv_addr->sin_addr.s_addr = inet_addr("127.0.0.1"); //具体的IP地址
  7. serv_addr->sin_port = htons(11234); //端口
  8. int on = 1;
  9. if (setsockopt(serv_sock, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on)) == -1) {
  10. printf("处理失败SO_REUSEPORT失败");
  11. exit(1);
  12. }
  13. bind(serv_sock, (struct sockaddr *) serv_addr, sizeof(struct sockaddr));
  14. listen(serv_sock, 20);
  15. for (;;) {
  16. int fd = accept(serv_sock, NULL, NULL);
  17. char *hello = "hello chenshun!";
  18. char cc[20];
  19. ssize_t rr = read(fd, cc, 10);
  20. if (rr == -1) {
  21. close(fd);
  22. }
  23. printf("i receive your message:%s\n", cc);
  24. write(fd, hello, strlen(hello));
  25. write(fd, "good bye!", strlen("good bye!"));
  26. close(fd);
  27. }
  28. return 0;
  29. }