/*---------------------------------------------------------------------------------------------- ÆÄÀϸí : chat_server.c ±â ´É : äÆà Âü°¡ÀÚ °ü¸®, äÆà ¸Þ½ÃÁö ¼ö½Å ¹× ¹æ¼Û ÄÄÆÄÀÏ : cc -o chat_server chat_server.c readline.c -lsocket -lnsl ½ÇÇ࿹ : chat_server 4001 -----------------------------------------------------------------------------------------------*/ #include #include #include #include #include #include #include #define MAXLINE 1024 #define MAX_SOCK 512 char *escapechar = "exit\n"; int readline(int, char *, int); int main(int argc, char *argv[]) { char rline[MAXLINE], my_msg[MAXLINE]; char *start = "´ëÈ­¹æ¿¡ ¿À½Å°É ȯ¿µÇÕ´Ï´Ù...\n"; int i, j, n; int s, client_fd, clilen; int nfds; /* ÃÖ´ë ¼ÒÄϹøÈ£ +1 */ fd_set read_fds; /* Àб⸦ °¨ÁöÇÒ ¼ÒÄϹøÈ£ ±¸Á¶Ã¼ */ int num_chat = 0; /* äÆà Âü°¡ÀÚ ¼ö */ /* äÆÿ¡ Âü°¡Çϴ Ŭ¶óÀ̾ðÆ®µéÀÇ ¼ÒÄϹøÈ£ ¸®½ºÆ® */ int client_s[MAX_SOCK]; struct sockaddr_in client_addr, server_addr; if(argc < 2) { printf("½ÇÇà¹æ¹ý :%s Æ÷Æ®¹øÈ£\n",argv[0]); return -1; } printf("´ëÈ­¹æ ¼­¹ö ÃʱâÈ­ Áß....\n"); /* Ãʱâ¼ÒÄÏ »ý¼º */ if((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) { printf("Server: Can't open stream socket."); return -1; } /* server_addr ±¸Á¶Ã¼ÀÇ ³»¿ë ¼¼Æà */ bzero((char *)&server_addr, sizeof(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])); if (bind(s,(struct sockaddr *)&server_addr,sizeof(server_addr)) < 0) { printf("Server: Can't bind local address.\n"); return -1; } /* Ŭ¶óÀ̾ðÆ®·ÎºÎÅÍ ¿¬°á¿äûÀ» ±â´Ù¸² */ listen(s, 5); nfds = s + 1; /* ÃÖ´ë ¼ÒÄϹøÈ£ +1 */ FD_ZERO(&read_fds); while(1) { /* (ÃÖ´ë ¼ÒÄϹøÈ£ +1) °ªÀ» °»½Å */ if((num_chat-1) >= 0) nfds = client_s[num_chat-1] + 1; /* Àб⠺¯È­¸¦ °¨ÁöÇÒ ¼ÒÄϹøÈ£¸¦ fd_set ±¸Á¶Ã¼¿¡ ÁöÁ¤ */ FD_SET(s, &read_fds); for(i=0; i 0) { rline[n] = '\0'; /* Á¾·á¹®ÀÚ ÀԷ½à äÆà ŻÅð ó¸® */ if (exitCheck(rline, escapechar, 5) == 1) { shutdown(client_s[i], 2); if(i != num_chat-1) client_s[i] = client_s[num_chat-1]; num_chat--; continue; } /* ¸ðµç äÆà Âü°¡ÀÚ¿¡°Ô ¸Þ½ÃÁö ¹æ¼Û */ for (j = 0; j < num_chat; j++) send(client_s[j], rline, n, 0); printf("%s", rline); } } } } } /* ------------------------------- Á¾·á¹®ÀÚ È®ÀÎ ÇÔ¼ö ---------------------------- exitCheck()´Â ´ÙÀ½ÀÇ ¼¼ °³ÀÇ ÀÎÀÚ¸¦ ÇÊ¿ä·Î ÇÑ´Ù rline: Ŭ¶óÀ̾ðÆ®°¡ Àü¼ÛÇÑ ¹®ÀÚ¿­ Æ÷ÀÎÅÍ escapechar: Á¾·á¹®ÀÚ Æ÷ÀÎÅÍ len: Á¾·á¹®ÀÚÀÇ Å©±â ---------------------------------------------------------------------------------------------*/ int exitCheck(rline, escapechar, len) char *rline; /* Ŭ¶óÀ̾ðÆ®°¡ Àü¼ÛÇÑ ¸Þ½ÃÁö */ char *escapechar; /* Á¾·á¹®ÀÚ */ int len; { int i, max; char *tmp; max = strlen(rline); tmp = rline; for(i = 0; i