/*------------------------------------------------------------------------------------------------------------ ÆÄÀϸí : talk_server.c ±â ´É : ÅäÅ© Ŭ¶óÀ̾ðÆ®¿Í 1:1 Åë½ÅÀ» ÇÑ´Ù. ÄÄÆÄÀÏ : cc -o talk_server talk_server.c readline.c -lsocket -lnsl »ç¿ë¿¹ : talk_server 3000 -------------------------------------------------------------------------------------------------------------*/ #include #include #include #include #include #include #include #define MAXLINE 1024 int readline(int, char *, int); char *escapechar = "exit\n"; /* Á¾·á¹®ÀÚ */ int main(int argc, char *argv[]) { int server_fd, client_fd; /* ¼ÒÄϹøÈ£ */ int clilen, num; char sendline[MAXLINE], rbuf[MAXLINE]; int size; pid_t pid; struct sockaddr_in client_addr, server_addr; if (argc < 2) { printf("Usage: %s TCP_PORT\n", argv[0]); return -1; } /* ¼ÒÄÏ »ý¼º */ if((server_fd=socket(PF_INET, SOCK_STREAM, 0)) < 0) { printf("Server: Can't open stream socket\n"); return -1; } /* ¼­¹öÀÇ ¼ÒÄÏÁÖ¼Ò ±¸Á¶Ã¼ server_addrÀ» '0'À¸·Î ÃʱâÈ­ */ bzero((char *)&server_addr, sizeof(server_addr)); /* server_addrÀ» ¼¼Æà */ server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(atoi(argv[1])); /* bind() È£Ãâ */ if(bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { printf("Server: Can't bind local address \n"); return -1; } printf("Server started.\nWaiting for client.."); listen(server_fd, 1); /* Ŭ¶óÀ̾ðÆ® ¿¬°á¿äû ¼ö¶ô */ clilen = sizeof(client_addr); if((client_fd = accept(server_fd,(struct sockaddr *)&client_addr, &clilen)) != -1) { printf("Server: client connected\n"); } else { printf("Server: failed in accepting.\n"); return -1; } /* ºÎ¸ð ÇÁ·Î¼¼½º´Â Å°º¸µå ÀÔ·ÂÀ» Ŭ¶óÀ̾ðÆ®¿¡°Ô Àü¼Û */ if((pid = fork()) > 0) { while(readline(0, sendline, MAXLINE) != 0) { size = strlen(sendline); if(write(client_fd, sendline, size) != size) { printf("Server: fail in writing\n"); } /* Á¾·á ¹®ÀÚ¿­ ÀÔ·Â È®ÀÎ */ if(strncmp(sendline, escapechar, 4) == 0) { kill(pid, SIGQUIT); break; } } /* ÀÚ½ÄÇÁ·Î¼¼½º´Â ¼ÒÄÏÀ¸·ÎºÎÅÍ µé¾î¿À´Â ¸Þ½ÃÁö¸¦ È­¸é¿¡ Ãâ·Â */ } else if (pid == 0) { while(1) { if((size = read(client_fd, rbuf, MAXLINE)) > 0) { rbuf[size] = '\0'; /* Á¾·á¹®ÀÚ¿­ ¼ö½Å ó¸® */ if (strncmp(rbuf, escapechar, 4) == 0) break; printf("%s", rbuf); } } } close(server_fd); close(client_fd); }