TCP併發ECHO服務器——線程版

#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<pthread.h>
#include<unistd.h>
//TCP併發ECHO服務器(併發回執服務器----你給服務器發啥,服務器給你回啥)
void * deal_client_fun(void *arg)
{
	//併發服務器的核心代碼(各不相同)
	//通過arg獲得已連接套接字
	int fd = *(int *)arg;
	while(1)//服務器的核心代碼
	{
		//獲取客戶端請求
		char buf[128]="";
		int len = recv(fd,buf,sizeof(buf),0);
		if(len == 0)
			break;
		//迴應客戶端
		send(fd,buf,len,0);	
	}
	close(fd);
	
}
int main()
{
	//創建套接字
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(sockfd<0)
	{
		perror("socket");
	}
	//bind綁定
	struct sockaddr_in my_addr;
	bzero(&my_addr,sizeof(my_addr));
	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(8000);
	my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	bind(sockfd,(struct sockaddr *)&my_addr,sizeof(my_addr));
	
	//listen創建連接隊列
	listen(sockfd,10);
	
	
	//accept從連接隊列提取已完成連接,得到已連接套接字
	////accept調用一次只能提取一個客戶端
	while(1)
	{
		struct sockaddr_in cli_addr;
		socklen_t cli_len=sizeof(cli_addr);
		int new_fd = accept(sockfd,(struct sockaddr *)&cli_addr,&cli_len);
		
		//遍歷客戶端信息ip
		char ip[16]="";
		
		inet_ntop(AF_INET,&cli_addr.sin_addr.s_addr,ip,16);
		unsigned short port=ntohs(cli_addr.sin_port);
		printf("已有客戶端:%s:%hu連接上了服務器\n",ip,port);
		
		//對每個客戶端 開啓一個線程 單獨的服務器客戶端
		pthread_t tid;
		pthread_create(&tid,NULL,deal_client_fun,(void *)&new_fd);
		
		//線程分離 線程本身去回收資源
		pthread_detach(tid);
		
	}
	
	close(sockfd);
	
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章