上一篇博文讲了如何利用子进程实现多个客户端和服务器端进行通信,
那么,这一篇博客就来实现一下如何利用线程实现多个客户端和服务器端进行通信
代码实现:
ser1.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <pthread.h> void *fun(void *arg) { int c = (int)arg; while(1) { char buff[128] = {0}; if(recv(c,buff,127,0) <= 0) { break; } printf("buff = %s",buff); send(c,"OK",2,0); } close(c); pthread_exit(NULL); } int main() { int sockfd = socket(AF_INET,SOCK_STREAM,0);//tcp assert(sockfd != -1); struct sockaddr_in saddr,caddr; memset(&saddr,0,sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(6000); saddr.sin_addr.s_addr = inet_addr("127.0.0.1"); int res = bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr)); assert(res != -1); listen(sockfd,5); while(1) { int len = sizeof(caddr); int c = accept(sockfd,(struct sockaddr*)&caddr,&len); if(c < 0) { continue; } printf("accept: c = %d,ip:%s,port:%d\n",c,inet_ntoa(caddr.sin_addr),ntohs(caddr.sin_port)); pthread_t id; pthread_create(&id,NULL,fun,(void*)c); } }
cli1.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <unistd.h> #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> 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(6000); saddr.sin_addr.s_addr = inet_addr("127.0.0.1"); int res = connect(sockfd,(struct sockaddr*)&saddr,sizeof(saddr)); assert(res != -1); while(1) { printf("input :"); char buff[128] = {0}; fgets(buff,128,stdin); if(strncmp(buff,"end",3) == 0) { break; } send(sockfd,buff,strlen(buff),0); memset(buff,0,128); recv(sockfd,buff,127,0); printf("buff = %s\n",buff); } close(sockfd); }
运行结果: