基于Linux网络编程的聊天室

服务端只负责读,客户端只负责写

服务端程序:
#include  
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
int s_fd;
int c_fd;
pthread_t t1;
void *pthread_handler();
int main(int argc,char **argv)
{
	s_fd = socket(AF_INET,SOCK_STREAM,0);//建立服务器

	if(s_fd == -1)
	{
		perror("sccket");
		exit(-1);
	}
	struct sockaddr_in s_addr;
	struct sockaddr_in c_addr;
	memset(&s_addr,0,sizeof(struct sockaddr_in));
	memset(&c_addr,0,sizeof(struct sockaddr_in));
	int clen;
	clen = sizeof(struct sockaddr_in);

	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(atoi(argv[2])); 
	inet_aton(argv[1],&s_addr.sin_addr);

	bind(s_fd,(struct sockaddr *)&s_addr,sizeof(struct sockaddr_in));//连接到套接字

	listen(s_fd,10);

			
	while(1)
	{
		c_fd = accept(s_fd,(struct sockaddr *)&c_addr,&clen);//一直等待客户端连接,返回值是客户端建立的套接字
		printf("client %d is connect:\n",c_fd);
		if(c_fd == -1)
		{
			perror("accept");
		}
		printf("get connect:%s  %d\n",inet_ntoa(c_addr.sin_addr),c_fd);
		pthread_create(&t1,NULL,pthread_handler,NULL);
	}                       



	return 0;
}
void *pthread_handler()
{

	memset(&readbuf,0,strlen(readbuf));
	char readbuf[128] = {0};
	printf("pthread creat success\n");
	while(1)//父进程读
	{       
		
		int n_read = read(c_fd,readbuf,128);
		if(n_read == -1)
		{
			perror("read");
			exit(-1);
		}
		else
		{
			printf("read msg from:%d  %s\n",n_read,readbuf);
		}
		
	}
}

客户端代码:
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
char readbuf[128] = {0};

int c_fd;
int main(int argc,char **argv)
{
	pthread_t t1;
	struct sockaddr_in c_addr;
	char msg[128] = {0};
	c_fd = socket(AF_INET,SOCK_STREAM,0);
	memset(&c_addr,0,sizeof(struct sockaddr_in));

	if(c_fd == -1)
	{
		perror("sccket");
		exit(-1);
	}
	c_addr.sin_family = AF_INET;
	c_addr.sin_port = htons(atoi(argv[2]));
	inet_aton(argv[1],&c_addr.sin_addr);
	if(connect(c_fd,(struct sockaddr *)&c_addr,sizeof(struct sockaddr_in)) == -1)
	{
		perror("connect");
		exit(-1);
	}
	else//否则连接到了服务器
	{
		while(1)//子进程是客户端,不断写数据
		{
			memset(&msg,0,strlen(msg));
			printf("please input your msg:\n");
			gets(msg);//数据写到msg里面
			write(c_fd,msg,strlen(msg));//写到套接字里面
		}

	}
	return 0;
}


你可能感兴趣的:(Linux,linux,网络,运维)