/*** server.c ***/ #include<stdio.h> #include<fcntl.h> #include<string.h> #include<netinet/in.h> #include<arpa/inet.h> #include<signal.h> #include<sys/wait.h> #include<ctype.h> #include<unistd.h> #include<pthread.h> #include"wrap.h" #define MAXLINE 8192 #define SERV_PORT 8000 struct s_info { struct sockaddr_in cliaddr; int connfd; }; void *do_work(void *arg) { int n,i; struct s_info *ts = (struct s_info*)arg; char buf[MAXLINE]; char str[INET_ADDRSTRLEN]; while(1) { n = Read(ts->connfd,buf,MAXLINE) ; if( 0 == n) { printf("the client %d close... ",ts->connfd) ; break; } printf("received from %s at PORT:%d ", inet_ntop(AF_INET,&(*ts).cliaddr.sin_addr,str,sizeof(str)), ntohs((*ts).cliaddr.sin_port)); for(i = 0 ; i < n; i++) buf[i] = toupper(buf[i]); Write(STDOUT_FILENO,buf,n); Write(ts->connfd,buf,n); } close(ts->connfd); return (void*)0; } int main() { struct sockaddr_in servaddr,cliaddr; socklen_t cliaddr_len; int listenfd,connfd; pthread_t tid; struct s_info ts[256]; int i = 0; listenfd = Socket(AF_INET,SOCK_STREAM,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(SERV_PORT); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); //inet_pton(AF_INET,"192.168.0.1",&serv_addr.sin_addr.s_addr); Bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); Listen(listenfd,128); printf("Accepting client connect ... "); while(1) { cliaddr_len = sizeof(cliaddr); connfd = Accept(listenfd,(struct sockaddr *)&cliaddr,&cliaddr_len); ts[i].cliaddr = cliaddr; ts[i].connfd = connfd; pthread_create(&tid,NULL,do_work,(void *)&ts[i]); pthread_detach(tid); i++; } return 0; }
/*** makefile ***/ src = $(wildcard *.c) obj = $(patsubst %.c, %.o, $(src)) all: server client server: server.o wrap.o gcc server.o wrap.o -o server -Wall -lpthread client: client.o wrap.o gcc client.o wrap.o -o client -Wall -lpthread %.o:%.c gcc -c $< -Wall .PHONY: clean all clean: -rm -rf server client $(obj)
makefile主要是添加了-lpthread线程库
这是服务器编写代码,客户端代码可以使用上篇,也可以使用命令:nc + IP地址+端口号来代替客户端作用
运行结果:
还使用了wrap.c和wrap.h文件,在上篇博客有,这里就重复使用了。