【聊天室】服务器server的代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define PORT 33333  //定义网络端口号

void *recv_message(void *arg)
{
	int cfd = *((int *)arg);
	int ret;
	char buffer[1024];
	
	while(1)
	{
		memset(buffer,0,sizeof(buffer));
		if((ret = recv(cfd,buffer,sizeof(buffer),0)) < 0)
		{
			perror("recv error!\n");
			exit(1);
		}
		if(ret == 0)
		{
			printf("%d is close!\n",cfd);
			pthread_exit(NULL);
		}
		printf("recv is %s\n",buffer);
		usleep(3);
	}
	pthread_exit(NULL);
}

void *send_message(void *arg)
{
	int cfd = *((int *)arg);
	int ret;
	char buffer[1024];
	
	while(1)
	{
		if((ret = send(cfd,"helloworld",12,0)) < 0)
		{
			perror("send error!\n");
			exit(1);
		}
		if(ret == 0)
		{
			printf("%d is close!\n",cfd);
			pthread_exit(NULL);
		}
		sleep(1);
	}
	pthread_exit(NULL);
}



int main()
{
	int sockfd;
	int cfd;
	int c_len;
	pthread_t id;
	
	char buffer[1024];
	
	struct sockaddr_in s_addr;
	struct sockaddr_in c_addr;
	
	sockfd = socket(AF_INET,SOCK_STREAM,0);
	
	if(sockfd < 0)
	{
		perror("socket creat error!");
		exit(1);
	}	
	printf("socket success!\n");
	
	int opt = 1;
	
	setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
	
	bzero(&s_addr,sizeof(struct sockaddr_in));
	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(PORT);
	s_addr.sin_addr.s_addr = inet_addr("192.168.1.17");
	
	if(bind(sockfd,(struct sockaddr *)(& s_addr),sizeof(struct sockaddr_in)) < 0)
	{
		perror("bind error!");
		exit(1);
	}
	printf("bind success!\n");
	
	if(listen(sockfd,3) < 0)
	{
		perror("listen error!\n");
		exit(1);
	}
	printf("listen success!\n");
	
	while(1)
	{
		memset(buffer,0,sizeof(buffer));
		
		bzero(&c_addr,sizeof(struct sockaddr_in));
		c_len = sizeof(struct sockaddr_in);
		
		printf("accept........!\n");
		
		cfd = accept(sockfd,(struct sockaddr *)(&c_addr),&c_len);
		
		if(cfd < 0)
		{
			perror("accept error!\n");
			exit(1);
		}
		
		printf("port = %d ip = %s\n",ntohs(c_addr.sin_port),inet_ntoa(c_addr.sin_addr));
		
		if(pthread_create(&id, NULL,recv_message,(void *)(&cfd)) != 0)
		{
			perror("thread error!\n");
			exit(1);
		}
		
		if(pthread_create(&id, NULL,send_message,(void *)(&cfd)) != 0)
		{
			perror("thread error!\n");
			exit(1);
		}
		
		usleep(3);
	}
	return 0;
}

你可能感兴趣的:(【聊天室】服务器server的代码)