C语言实现多人聊天(udp)

Posted 想文艺一点的程序员

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C语言实现多人聊天(udp)相关的知识,希望对你有一定的参考价值。

  • server 端
#include <stdio.h> //printf
#include <arpa/inet.h> //inet_addr htons
#include <sys/types.h>
#include <sys/socket.h> //socket bind listen accept connect
#include <netinet/in.h> //sockaddr_in
#include <stdlib.h> //exit
#include <unistd.h> //close
#include <string.h>
 
#define N 128
#define ERRLOG(errmsg) do{\\
								perror(errmsg);\\
								printf("%s -- %s -- %d\\n", __FILE__, __func__, __LINE__);\\
								exit(1);\\
							 }while(0)
typedef struct{
	int key;
	char name[N];
	char data[N];
}MSG;
 
typedef struct node{
	//虽然传递过来的信息为MSG但是我们需要保存的是传递过来的
	//网络信息结构体
	struct sockaddr_in addr;
	struct node *next;
}linklist_t;
 
linklist_t *linklist_create()
{
	linklist_t *p = (linklist_t *)malloc(sizeof(linklist_t));
	p->next = NULL;
	return p;
}
void do_quit(int sockfd,MSG msg, linklist_t *p,struct sockaddr_in client_addr);
void do_chat(int sockfd,MSG msg, linklist_t *p,struct sockaddr_in client_addr);
void do_login(int sockfd,MSG msg, linklist_t *p,struct sockaddr_in client_addr);

int main(int argc, const char *argv[])
{
	int sockfd;
	struct sockaddr_in server_addr, client_addr;	//这里定义client的目的也是保存client的信息
	socklen_t addrlen = sizeof(struct sockaddr_in);
	MSG msg;
	if(argc < 3)
	{
		fprintf(stderr, "Usage: %s <ip> <port>\\n", argv[0]);
		exit(1);
	}
	if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		ERRLOG("fail to socket");
	}
	// server中填写server的网络信息结构体
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = inet_addr(argv[1]);
	server_addr.sin_port = htons(atoi(argv[2]));
 
	// bind网络信息结构体
	if(bind(sockfd, (struct sockaddr *)&server_addr, addrlen) < 0)
	{
		ERRLOG("fail to bind");
	}
 
	pid_t pid;
	if((pid = fork()) < 0)
	{
		ERRLOG("fail to fork");
	}
	//-------------父进程---------------------
	else if(pid > 0)	
	{	
		while(1)
		{
 
		}
	}
	//-------------子进程接收消息---------------
	else 					
	{
		//初始化链表
		linklist_t *p = linklist_create();
		while(1)
		{
			//printf("recv 上\\n");
			recvfrom(sockfd, &msg, sizeof(msg), 0, (struct sockaddr *)&client_addr, &addrlen);
			//printf("recv 下\\n");
			//接收到消息后要判断 携带的key是什么类型
			//printf("---recv---")
			switch(msg.key)
			{
				case 1:
					do_login(sockfd, msg, p, client_addr);
					break;
				case 2:
					do_chat(sockfd, msg, p, client_addr);
					break;
				case 3:
					do_quit(sockfd, msg, p, client_addr);
					break;
			}
		}
	}
	return 0;
}
 
void do_login(int sockfd,MSG msg, linklist_t *p,struct sockaddr_in client_addr)	//登录功能,需要保存用户信息在函数中
{
//printf("login");
	sprintf(msg.data, "-----name: %s is login-----------",msg.name);
//	char buf[N] = {};
//	strcpy(buf, msg.name);
	printf("%s\\n",msg.data);
	linklist_t *h = p;
 
	int len = sizeof(client_addr);
	//遍历链表,向客户端发送用户登录的消息
	while(h->next != NULL)
	{	
		sendto(sockfd, &msg, sizeof(msg), 0,(struct sockaddr *)&p->next->addr, len);
		h = h->next;
		//printf("sendto ok\\n");
	}
 
	//不先保存客户的信息 因为要发送给除这个用户的所有的信息.
	linklist_t *temp = (linklist_t *)malloc(sizeof(linklist_t));
 
	temp->addr = client_addr;
	temp->next = p->next;
	p->next = temp;
	return;	
}
 
void do_chat(int sockfd,MSG msg, linklist_t *p,struct sockaddr_in client_addr)
{
	char buf[N];
	sprintf(buf, "%s : %s",msg.name, msg.data);
	strcpy(msg.data, buf);
	int len = sizeof(client_addr);
	while((p->next != NULL) )
	{	
		if( memcmp(&(p->next->addr),&client_addr,sizeof(client_addr)) == 0)
		{
			p = p->next;
		}
		else
		{
			sendto(sockfd, &msg, sizeof(msg), 0,(struct sockaddr *)&p->next->addr, len);
			p = p->next;
			//printf("sendto ok\\n");
		}
	}
	return;
}
 
void do_quit(int sockfd,MSG msg, linklist_t *p,struct sockaddr_in client_addr)
{
	linklist_t *h = p;
	sprintf(msg.data, "-----%s is offline------\\n",msg.name);
	printf("%s\\n",msg.data);

	while(memcmp(&h->next->addr,&client_addr,sizeof(client_addr)) != 0)
	{
		h = h->next;
	}
	linklist_t *temp = h->next;
	h->next = h->next->next;
	free(temp);
	temp = NULL;
//	printf("while上\\n");
	while(p->next != NULL)
	{
//		printf("sendto上\\n");
		sendto(sockfd, &msg, sizeof(msg), 0,(struct sockaddr *)&p->next->addr, sizeof(struct sockaddr_in));
//		printf("sendto下\\n");
		p = p->next;
	}
 
}
  • client 端
#include <stdio.h> //printf
#include <arpa/inet.h> //inet_addr htons
#include <sys/types.h>
#include <sys/socket.h> //socket bind listen accept connect
#include <netinet/in.h> //sockaddr_in
#include <stdlib.h> //exit
#include <unistd.h> //close
#include <string.h>
 
#define N 128
#define ERRLOG(errmsg) do{\\
								perror(errmsg);\\
								printf("%s -- %s -- %d\\n", __FILE__, __func__, __LINE__);\\
								exit(1);\\
							 }while(0)
typedef struct{
	int key;
	char name[N];
	char data[N];
}MSG;
 
 
 
int main(int argc, const char *argv[])
{
	int sockfd;
	struct sockaddr_in server_addr;	
	socklen_t addrlen = sizeof(struct sockaddr_in);
 
	if(argc < 3)
	{
		fprintf(stderr, "Usage: %s <ip> <port>\\n", argv[0]);
		exit(1);
	}
	if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		ERRLOG("fail to socket");
	}
	//自己的网络信息结构体能由系统自动生成
	//client 中填写的是 server的网络信息结构体,因为要
	//让client的sockfd和server的网络信息相绑定
	//就能实现与服务器相通信
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = inet_addr(argv[1]);
	server_addr.sin_port = htons(atoi(argv[2]));
 
	//bind网络信息结构体
//	if(bind(sockfd, (struct sockaddr *)&server_addr, addrlen) < 0)
//	{
//		ERRLOG("fail to bind");
//	}
	//首先服务器需要发送自己的姓名给客户端
	
	MSG msg;
	bzero(&msg, sizeof(msg));
	printf("please enter your name:");
	msg.key = 1;
//	scanf("%s",msg.name);
	fgets(msg.name, N, stdin);
	msg.name[strlen(msg.name) - 1] = '\\0';
	//printf("send 上\\n");
	if((sendto(sockfd, &msg, sizeof(msg), 0, (struct sockaddr *)&server_addr,addrlen)) < 0)
	{
		ERRLOG("fail to sendto");
	}
	//printf("send 下\\n ");
	pid_t pid;
	pid = fork();
	if(pid > 0)
	{
		while(1)
		{
			fgets(msg.data, N, stdin);
			msg.key = 2;
			msg.data[strlen(msg.data) - 1] = '\\0';
			if(strcmp(msg.data,"quit") == 0)
			{
				msg.key = 3;
			}
			if((sendto(sockfd, &msg, sizeof(msg), 0, (struct sockaddr *)&server_addr,addrlen)) < 0)
			{
				ERRLOG("fail to sendto");
			}
			if(msg.key == 3)
			{
				sleep(1);
				return 0;
			}
		}
	}
	else if(pid == 0)
	{
		while(1)
		{
			//printf("recv上\\n");
			if((recvfrom(sockfd, &msg, sizeof(msg), 0, (struct sockaddr *)&server_addr,&addrlen)) < 0) 
			{
				ERRLOG("fail to sendto");
			}
			printf("%s\\n",msg.data);
		}
	}
	return 0;
}

以上是关于C语言实现多人聊天(udp)的主要内容,如果未能解决你的问题,请参考以下文章

WebSocket实现多人在线聊天功能

Java NIO实现的C/S模式多人聊天工具

linux C语言 TCP 多线程 简易聊天室

java 通过TCPUDP 协议实现多人聊天,点对点,文件传送-----分服务器端和客户端

C#实现多人视频聊天

nio 代码实现简易多人聊天