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
| #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <arpa/inet.h> #include <ctype.h>
#define IP "114.214.245.135" #define MaxLine 256 #define ServerPort 6666 #define MaxPending 10
int main(void) { struct sockaddr_in ServAddr, CliAddr; char buf[MaxLine]; int socketfd, connfd; int s,new_s,len;
socketfd=socket(PF_INET,SOCK_STREAM,0); if ((socketfd)<0) { perror("socket"); exit(1); } else printf("Socket create success!\n");
bzero((char *)&ServAddr, sizeof(ServAddr)); ServAddr.sin_family = AF_INET; ServAddr.sin_addr.s_addr=inet_addr(IP); ServAddr.sin_port=htons(ServerPort);
if ((bind(socketfd, (struct sockaddr*) &ServAddr,sizeof(struct sockaddr))) == -1) { perror("bind"); exit(1); } else printf("Bind success!\n"); listen(socketfd,MaxPending); if(listen(socketfd,MaxPending) == -1){ perror("listen"); exit(1); }else printf("the server is listening!\n");
while(1) { printf("*****************Start chatting***************\n"); len = sizeof(struct sockaddr); if ((new_s = accept(socketfd,(struct sockaddr*) &CliAddr, &len)) == -1) { perror("simplex-talk: accept"); exit(1); } else printf("You're chatting with:%s: %d\n",inet_ntoa(CliAddr.sin_addr),ntohs(CliAddr.sin_port));
while(1) { memset(buf,0,sizeof(buf)); fgets(buf,MaxLine,stdin); if(!strncasecmp(buf,"quit",4)) { printf("Server requires quitting\n"); break; } len = send(new_s,buf,strlen(buf),0); if(len > 0) printf("\tSend successfully:%s\n",buf); else { printf("Sending error\n"); break; } memset(buf,0,sizeof(buf)); len = recv(new_s, buf, sizeof(buf),0); if (len>0) printf("Client: %s\n",buf); else { if(len<0) printf("Receiving error"); else printf("Client quits."); break; } } printf("Chat end\n"); close(new_s); break; } close(socketfd); return 0; }
|