linux c tcp多线程并发服务端

#include <stdio.h>
#include <time.h>
#include <strings.h>
#include <ctype.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/socket.h>
#include <arpa/inet.h>

typedef struct sock_info{
	int cfd;
	struct sockaddr_in clie_addr;
	int num;
}s_info;

void print_error(const char *msg)
{
	perror(msg);
	exit(1);
}

void *get_msg(void *arg)
{
	s_info *s = (s_info *)arg;
	char ipbuf[BUFSIZ] = {};
	inet_ntop(AF_INET,&s->clie_addr.sin_addr.s_addr,ipbuf,sizeof(ipbuf));
	int n,i,port;
	port = ntohs(s->clie_addr.sin_port);
	printf("new client join ip:%s port:%d number:%d\n",ipbuf,port,s->num);
	char buffer[BUFSIZ];
	while(1)
	{
		bzero(buffer,0);
		n = read(s->cfd,buffer,sizeof(buffer));
		if (n == 0)
		{
			printf("client ip:%s num:%d exit\n",ipbuf,s->num);
			break;
		}
		time_t t;
		time(&t);
		struct tm *tm = localtime(&t);

		printf("ip:%s:%d %2d-%2d %2d:%2d:%2d\n%s\n",ipbuf,port,
					tm->tm_mon + 1,
					tm->tm_mday,
					tm->tm_hour,
					tm->tm_min,
					tm->tm_sec,
					buffer);
		for(i = 0;i<n;i++)
			buffer[i] = toupper(buffer[i]);
		write(s->cfd,buffer,n);
	}
	close(s->cfd);
	free(s);
	return NULL;
}

int main(int argc,char **argv)
{	
	int sfd = socket(AF_INET,SOCK_STREAM,0);
	if (sfd == -1)
	{
		print_error("socket");
	}
	struct sockaddr_in serv_addr,clie_addr;
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(8888);
	//serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	inet_pton(AF_INET,"192.168.2.144",&serv_addr.sin_addr.s_addr);
	int result = bind(sfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
	if (result == -1)
	{
		print_error("bind");
	}

	result = listen(sfd,128);
	if (result == -1)
	{
		print_error("listen");
	}
	int i = 0;
	while(1)
	{
		socklen_t clie_addr_len = sizeof(clie_addr);
		int cfd = accept(sfd,(struct sockaddr *)&clie_addr,&clie_addr_len);
		if (cfd == -1)
		{
			print_error("accept");
		}
		
		s_info *clie_sock = (s_info *)malloc(sizeof(s_info));
		clie_sock->cfd = cfd;
		clie_sock->clie_addr = clie_addr;
		clie_sock->num = i++;
		pthread_t id;
		pthread_create(&id,NULL,(void *)get_msg,(void *)clie_sock);
		pthread_detach(id);
	}
	return 0;
}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页