欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言实现匿名聊天(多客户端一服务器)

程序员文章站 2022-03-15 20:33:53
...

C语言实现匿名聊天(客户端之间)

客户端

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>

#define SER_IP "192.168.1.116"
void* send_func(void* arg);
void* recv_func(void* arg);

int main()
{
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(0 > sockfd)
	{
		perror("socket");
		return -1;
	}

	struct sockaddr_in addr = {};
	addr.sin_family = AF_INET;
	addr.sin_port = htons(7767);
	addr.sin_addr.s_addr = inet_addr(SER_IP);
	socklen_t len = sizeof(addr);

	if(connect(sockfd,(struct sockaddr*)&addr,len))
	{
		perror("bind");
		return -1;
	}

	pthread_t pid1;
	pthread_create(&pid1, NULL, recv_func, &sockfd);
	pthread_create(&pid1, NULL, send_func, &sockfd);		
	void* p = NULL;
	pthread_join(pid1, &p);
}


void* recv_func(void* arg)
{
	int sockfd = *(int*)arg;
	char buf[1024] = {};
	for(;;)
	{
		read(sockfd,buf,sizeof(buf));
		printf("%s\n",buf);
	}
}

void* send_func(void* arg)
{
	
	printf("what is your name :");
	char name[20] = {};
	gets(name);

	int sockfd = *(int*)arg;
	char buf[1024] = {};
	char buf1[2048] = {};
	for(;;)
	{
		gets(buf);
		sprintf(buf1,"%s:%s",name,buf);
		write(sockfd,buf1,strlen(buf1)+1);
		if(0 == strcmp("quit",buf))
		{
			printf("quit\n");
			pthread_exit(NULL);
		}
	}
}



服务器

#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>

int a[128];

bool exit(int fd)
{
	int i;
	for( i=0; a[i]; i++)
	{
		if(fd == a[i]) return true;
	}
	return false;
}

void* func(void* arg)	
{
	int newfd = *(int*)arg;
	
	char buf[1024] = {};
	int i;
	while(true)
	{
		read(newfd,buf,sizeof(buf));
		printf("%s\n",buf);
		if(0 == strcmp("quit",strchr(buf, ':')+1))
		{
			close(newfd);
			pthread_exit(NULL);
		}
		for(i=0; a[i]; i++)
		{
			if(a[i] != newfd)
			{
				write(a[i],buf,strlen(buf)+1);
			}
		}
	}
}

int main()
{
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(0 > sockfd)
	{
		perror("socket");
		return -1;
	}
	struct sockaddr_in addr = {};
	addr.sin_family = AF_INET;
	addr.sin_port = htons(7767);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	socklen_t len = sizeof(addr);
	if(bind(sockfd,(struct sockaddr*)&addr,len))
	{
		perror("bind");
		return -1;
	}
	if(listen(sockfd,128))
	{
		perror("listen");
		return -1;
	}
	int num = 0;
	printf("wait...\n");
	while(true)
	{
		struct sockaddr_in client_addr = {};
		int newfd = accept(sockfd,(struct sockaddr*)&client_addr,&len);
		if(0 > newfd)
		{
			perror("accept");
			continue;
		}	
		if(!exit(newfd))
		{
			a[num++] = newfd;
		}
		pthread_t pid;
		pthread_create(&pid, NULL, func, &newfd);
	}
}