并发TCP服务器端与客户端

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

#define PORT_SERVER 9898

int main()
{
	int socket_fd,fd;
	int nread;
	int size;
	char buffer[1024];
	struct sockaddr_in ad_s,ad_c;


	if((socket_fd=socket(AF_INET,SOCK_STREAM,0))==-1)
	{
		fprintf(stderr,"socket error\n");
		exit(1);
	}

	bzero(&ad_s,sizeof(ad_s));
	ad_s.sin_family=AF_INET;
	ad_s.sin_addr.s_addr=htonl(INADDR_ANY);
	ad_s.sin_port=htons(PORT_SERVER);

	if(bind(socket_fd,(struct sockaddr *)&ad_s,sizeof(ad_s))==-1)
	{
		fprintf(stderr,"bind error\n");
		exit(1);
	}
	
	if(listen(socket_fd,5)==-1)
	{
		fprintf(stderr,"listen error\n");
		exit(1);
	}

	while(1)
	{
		size=sizeof(struct sockaddr_in);
		bzero(buffer,1024);
		if((fd=accept(socket_fd,(struct sockaddr *)&ad_c,&size))==-1)
		{
			fprintf(stderr,"accept error\n");
			exit(1);
		}
		printf("server connect from %s\n",inet_ntoa(ad_c.sin_addr.s_addr));
		if(fork()==0)
		{
		if((nread=read(fd,buffer,1024))==-1)
		{
			fprintf(stderr,"read error\n");
			exit(1);
		}
		buffer[nread]='\0';
		printf("server receive %s\n",buffer);
		exit(0);
		}
		else
			close(fd);
	}
	close(socket_fd);
	exit(0);
}
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define PORT_CLIENT 9898

int main(int argv,char *argc[])
{
	struct hostent *host;
	if(argv<2)
	{
		perror("parameter error\n");
		exit(1);
	}
	if((host=gethostbyname(argc[1]))==NULL)
	{
		fprintf(stderr,"gethostname error\n");
		exit(1);
	}
	
	int sock_fd;
	struct sockaddr_in ad_s;
	char buffer[1024];

	if((sock_fd=socket(AF_INET,SOCK_STREAM,0))==-1)
	{
		fprintf(stderr,"socket error\n");
		exit(1);
	}
	bzero(&ad_s,sizeof(ad_s));
	ad_s.sin_family=AF_INET;
	ad_s.sin_port=htons(PORT_CLIENT);
	ad_s.sin_addr=*((struct in_addr*)host->h_addr);

	if(connect(sock_fd,(struct sockaddr *)&ad_s,sizeof(ad_s))==-1)
	{
		fprintf(stderr,"connect error\n");
		exit(1);
	}
	printf("input something...\n");
	bzero(buffer,1024);
	fgets(buffer,1024,stdin);
	write(sock_fd,buffer,strlen(buffer));

	close(sock_fd);
	exit(0);
}

《并发TCP服务器端与客户端》上的一个想法

发表回复

您的电子邮箱地址不会被公开。