1. #include "hl.h"
    2. #include<pthread.h>
    3. void cli_data_handle(void *arg);
    4. int main (int argc,char **argv)
    5. {
    6. int fd = -1;
    7. struct sockaddr_in sin;
    8. /* 1. 创建socket fd */
    9. if ((fd = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
    10. perror ("socket");
    11. exit (1);
    12. }
    13. int b_reuse = 1;
    14. setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&b_reuse,sizeof(int));
    15. /*2. 绑定 */
    16. /*2.1 填充struct sockaddr_in结构体变量 */
    17. bzero (&sin, sizeof (sin));
    18. sin.sin_family = AF_INET;
    19. sin.sin_port = htons (SERV_PORT); //网络字节序的端口号
    20. /*优化1: 让服务器程序能绑定在任意的IP上 */
    21. #if 1
    22. sin.sin_addr.s_addr = htonl (INADDR_ANY);
    23. #else
    24. if (inet_pton (AF_INET, SERV_IP_ADDR, (void *) &sin.sin_addr) != 1) {
    25. perror ("inet_pton");
    26. exit (1);
    27. }
    28. #endif
    29. /*2.2 绑定 */
    30. if (bind (fd, (struct sockaddr *) &sin, sizeof (sin)) < 0) {
    31. perror ("bind");
    32. exit (1);
    33. }
    34. /*3. 调用listen()把主动套接字变成被动套接字 */
    35. if (listen (fd, BACKLOG) < 0) {
    36. perror ("listen");
    37. exit (1);
    38. }
    39. printf ("Server starting....OK!\n");
    40. int newfd = -1;
    41. /*4. 阻塞等待客户端连接请求 */
    42. //pthread_t
    43. pthread_t tid;
    44. struct sockaddr_in cin;
    45. socklen_t addrlen = sizeof (cin);
    46. while(1)
    47. {
    48. if ((newfd = accept (fd, (struct sockaddr *) &cin, &addrlen)) < 0) {
    49. perror ("accept");
    50. exit (1);
    51. }
    52. char ipv4_addr[16];
    53. if (!inet_ntop (AF_INET, (void *) &cin.sin_addr, ipv4_addr, sizeof (cin))) {
    54. perror ("inet_ntop");
    55. exit (1);
    56. }
    57. printf ("Clinet(%s:%d) is connected!\n", ipv4_addr, htons (cin.sin_port));
    58. pthread_create(&tid,NULL,(void *)cli_data_handle,(void *)&newfd);
    59. }
    60. close (fd);
    61. return 0;
    62. }
    63. void cli_data_handle(void * arg)
    64. {
    65. int newfd = *(int *)arg;
    66. printf("handler thread:newfd=%d\n",newfd);
    67. //..和newfd进行数据读写
    68. int ret = -1;
    69. char buf[BUFSIZ];
    70. while (1) {
    71. bzero (buf, BUFSIZ);
    72. do {
    73. ret = read (newfd, buf, BUFSIZ - 1);
    74. } while (ret < 0 && EINTR == errno);
    75. if (ret < 0) {
    76. perror ("read");
    77. exit (1);
    78. }
    79. if (!ret) { //对方已经关闭
    80. break;
    81. }
    82. printf ("Receive data: %s\n", buf);
    83. if (!strncasecmp (buf, QUIT_STR, strlen (QUIT_STR))) { //用户输入了quit字符
    84. printf ("Client(fd=%d) is exiting!\n",newfd);
    85. break;
    86. }
    87. }
    88. close (newfd);
    89. }