1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/types.h> #include <unistd.h>
#define BUFLEN 10
int main(int argc, char *argv[]) { int sockfd, newfd; struct sockaddr_in s_addr, c_addr; char buf[BUFLEN]; socklen_t len; unsigned int port, listnum;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){ perror("socket"); exit(errno); } if(argv[2]) port = atoi(argv[2]); else port = 7777; if(argv[3]) listnum = atoi(argv[3]); else listnum = 3; bzero(&s_addr, sizeof(s_addr)); s_addr.sin_family = AF_INET; s_addr.sin_port = htons(port); if(argv[1]) s_addr.sin_addr.s_addr = inet_addr(argv[1]); else s_addr.sin_addr.s_addr = INADDR_ANY; if((bind(sockfd, (struct sockaddr*) &s_addr,sizeof(struct sockaddr))) == -1){ perror("bind"); exit(errno); } if(listen(sockfd,listnum) == -1){ perror("listen"); exit(errno); } while(1){ printf("*****************server start***************\n"); len = sizeof(struct sockaddr); if((newfd = accept(sockfd,(struct sockaddr*) &c_addr, &len)) == -1){ perror("accept"); exit(errno); } while(1){ _retry: bzero(buf,BUFLEN); printf("enter your words:"); fgets(buf,BUFLEN,stdin); if(!strncasecmp(buf,"quit",4)){ printf("server stop\n"); break; } if(!strncmp(buf,"\n",1)){
goto _retry; } if(strchr(buf,'\n')) len = send(newfd,buf,strlen(buf)-1,0); else len = send(newfd,buf,strlen(buf),0); if(len > 0) printf("send successful\n"); else{ printf("send failed\n"); break; } bzero(buf,BUFLEN); len = recv(newfd,buf,BUFLEN,0); if(len > 0) printf("receive massage:%s\n",buf); else{ if(len < 0 ) printf("receive failed\n"); else printf("client stop\n"); break; } } close(newfd); printf("exit?:y->yes;n->no "); bzero(buf, BUFLEN); fgets(buf,BUFLEN, stdin); if(!strncasecmp(buf,"y",1)){ printf("server stop\n"); break; } } close(sockfd); return 0; }
|