ser.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <assert.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <pthread.h> #include <fcntl.h> #define SER_PORT 6000 #define SER_IP "127.0.0.1" int socket_create(); void* thread_fun(void * arg); int main() { int sockfd = socket_create(); struct sockaddr_in caddr; while( 1 ) { int len = sizeof(caddr); int c = accept(sockfd,(struct sockaddr*)&caddr,&len); if ( c < 0 ) { continue; } printf("accept c = %d\n",c); pthread_t id; pthread_create(&id,NULL,thread_fun,(void*)c); } } void* thread_fun(void * arg) { int c = (int)arg; while( 1 ) { char buff[128] = {0}; int n = recv(c,buff,127,0);//rm a.c if ( n <= 0 ) { break; } //strtok_t -> rm, a.c -> myargv[], //1) get -> send_file() //2) put -> recv_file() //3) rm, cp , ls -> 创建管道 fork // parent -> read(pipefd[0]); // child -> dup2(pipefd[1],1) // dup2(pipefd[2],2) //exec(ls); //exit() printf("buff=%s\n",buff); send(c,"ok",2,0); } close(c); printf("one client over\n"); } int socket_create() { int sockfd = socket(AF_INET,SOCK_STREAM,0); if ( sockfd == -1 ) { return -1; } struct sockaddr_in saddr; memset(&saddr,0,sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(SER_PORT); saddr.sin_addr.s_addr = inet_addr(SER_IP); int res = bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr)); if ( res == -1 ) { return -1; } listen(sockfd,5); return sockfd; }
cli.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <assert.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <pthread.h> #include <fcntl.h> #define SER_PORT 6000 #define SER_IP "127.0.0.1" int main() { int sockfd = socket(AF_INET,SOCK_STREAM,0); assert ( sockfd != -1 ); struct sockaddr_in saddr; memset(&saddr,0,sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(SER_PORT); saddr.sin_addr.s_addr = inet_addr(SER_IP); int res = connect(sockfd,(struct sockaddr*)&saddr,sizeof(saddr)); assert( res != -1 ); while( 1 ) { char buff[128] = {0}; printf("Connect success>> "); fflush(stdout); fgets(buff,128,stdin);// ls , rm a.c, cp a.txt b.txt ,get a.c , put name if ( strncmp(buff,"end",3) == 0 ) { break; } send(sockfd,buff,strlen(buff),0); memset(buff,0,128); recv(sockfd,buff,127,0); printf("%s\n",buff); } close(sockfd); }