/*----------------------------------------------------------------------------------------- ÆÄÀϸí : chat_client.c ±â ´É : ¼­¹ö¿¡ Á¢¼ÓÇÑ ÈÄ Å°º¸µåÀÇ ÀÔ·ÂÀ» ¼­¹ö¿¡ Àü´ÞÇÏ°í, ¼­¹ö·ÎºÎÅÍ ¿À´Â ¸Þ½ÃÁö¸¦ È­¸é¿¡ Ãâ·ÂÇÑ´Ù. ÄÄÆÄÀÏ : cc -o chat_client chat_client.c readline.c -lsocket -lnsl ½ÇÇ࿹ : chat_client 203.252.65.3 4001 »ç¿ëÀÚ_ID -------------------------------------------------------------------------------------------*/ #include #include #include #include #include #include #define MAXLINE 1024 #define MAX_SOCK 512 char *escapechar = "exit\n"; int readline(int, char *, int); int s; /* ¼­¹ö¿Í ¿¬°áµÈ ¼ÒÄϹøÈ£ */ struct Name { char n[20]; /* ´ëÈ­¹æ¿¡¼­ »ç¿ëÇÒ À̸§ */ int len; /* À̸§ÀÇ Å©±â */ } name; int main(int argc, char *argv[]) { char line[MAXLINE], sendline[MAXLINE+1]; int n, pid, size; struct sockaddr_in server_addr; int nfds; fd_set read_fds; if( argc < 4 ) { printf("½ÇÇà¹æ¹ý : %s È£½ºÆ® IPÁÖ¼Ò Æ÷Æ®¹øÈ£ »ç¿ëÀÚÀ̸§ \n", argv[0]); return -1; } /* äÆà Âü°¡ÀÚ À̸§ ±¸Á¶Ã¼ ÃʱâÈ­ */ sprintf(name.n, "[%s]", argv[3]); name.len = strlen(name.n); /* ¼ÒÄÏ »ý¼º */ if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) { printf("Client : Can't open stream socket.\n"); return -1; } /* äÆà ¼­¹öÀÇ ¼ÒÄÏÁÖ¼Ò ±¸Á¶Ã¼ server_addr ÃʱâÈ­ */ bzero((char *)&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(argv[1]); server_addr.sin_port = htons(atoi(argv[2])); /* ¿¬°á¿äû */ if(connect(s, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { printf("Client : Can't connect to server.\n"); return -1; } else { printf("Á¢¼Ó¿¡ ¼º°øÇß½À´Ï´Ù..\n"); } nfds = s + 1; FD_ZERO(&read_fds); while(1) { /* -------------------------------------- selelct() È£Ãâ ---------------------------------------/* FD_SET(0, &read_fds); FD_SET(s, &read_fds); if(select(nfds, &read_fds, (fd_set *)0, (fd_set *)0, (struct timeval *)0) < 0) { printf("select error\n"); return -1; } /*------------------------- ¼­¹ö·ÎºÎÅÍ ¼ö½ÅÇÑ ¸Þ½ÃÁö ó¸® -------------------------*/ if (FD_ISSET(s, &read_fds)) { char recvline[MAXLINE]; int size; if ((size = recv(s, recvline, MAXLINE, 0)) > 0) { recvline[size] = '\0'; printf("%s \n", recvline); } } /* --------------------------------- Å°º¸µå ÀԷ ó¸® ----------------------------------*/ if (FD_ISSET(0, &read_fds)) { if (readline(0, sendline, MAXLINE) > 0) { size = strlen(sendline); sprintf(line, "%s %s", name.n, sendline); if (send(s, line, size + name.len, 0) != (size+name.len)) printf("Error : Written error on socket.\n"); if (size == 5 && strncmp(sendline, escapechar, 5) == 0) { printf("Good bye.\n"); close(s); return -1; } } } /* end of Å°º¸µå ÀԷ ó¸® */ } /* end of while() */ }