4.16 网络编程作业

1.基于UDP的网络聊天室

1.服务器

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

#define ERR_MSG(msg) do{\
	fprintf(stderr,"lien:%d ",__LINE__);\
	perror("msg");\
}while(0)

#define SER_IP "192.168.8.53"
#define SER_PORT 6666

int sfd=0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; 

//定义协议
typedef struct msg{
	char type;
	char name[20];
	char text[64];
}info;

typedef struct Node
{
	struct sockaddr_in cin;
	struct msg inform;
	struct Node *next;
}UsrNode;

typedef struct head
{
	int len;
	UsrNode *next; //指向用户链表类型
}UsrList;

UsrList *headlist=NULL;
ssize_t res=0;

//群发给链表中已登入的客户端 保存新的客户端
int do_login(UsrNode *usrline)
{
	UsrNode *cur=headlist->next;

	//服务器组装用户登入信息
	info msgbuf;
	strcpy(msgbuf.name,usrline->inform.name);
	strcpy(msgbuf.text,"用户登入");
	pthread_mutex_lock(&lock); 

	for(int i=0;i<headlist->len;i++,cur=cur->next)//
	{
		if(0 == memcmp(&(usrline->cin),&(cur->cin),sizeof(struct sockaddr_in)))
		{
			printf("%s用户已经存在\n",usrline->inform.name);
			pthread_exit(NULL);
		}
	}

	cur =headlist->next;  //将cur重新指向头结点的下一位
	for(int i=0;i<headlist->len;i++,cur=cur->next)//大概段错误的地方,原先是while循环
	{
		res = sendto(sfd,&msgbuf,sizeof(msgbuf),0,(struct sockaddr*)&(cur->cin),sizeof(cur->cin));
		if(res<0)
		{
			ERR_MSG("sendto");
			return -1;
		}
	}

	//保存新的客户端信息到链表
	usrline->next=headlist->next;
	headlist->next=usrline;
	headlist->len++;
	printf("添加%s:用户完毕",usrline->inform.name);

	pthread_mutex_unlock(&lock); 
	return 0;
}

int do_quit(UsrNode *usrline)
{
	//如果协议为下线,则将下线者的客户端信息发送给所有上线的客户端,并将下线的用户从链表中移除
	UsrNode *cur=headlist->next;//用于遍历链表
	UsrNode *del=headlist->next;//用于删除节点
	ssize_t res=0;

	info msgbuf;
	//组下线信息包
	strcpy(msgbuf.name,usrline->inform.name);
	strcpy(msgbuf.text,"用户已下线");

	pthread_mutex_lock(&lock);
	//链表表头就是需要删除的节点的情况
	if(memcmp(&(usrline->cin),&(cur->cin),sizeof(struct sockaddr_in))==0)
	{
		while(cur->next!=NULL)
		{
			//先移动到cur的下一个节点上再发送到节点上存储的地址信息
			cur=cur->next;
			if(sendto(sfd,(&msgbuf),sizeof(msgbuf),0,(struct sockaddr*)&(cur->cin),sizeof(cur->cin))<0)
			{
				ERR_MSG("sendto");
				return -1;
			}
		}

		headlist->next=del->next;
		headlist->len--;
		free(del);
	}
	else
	{
		//若为其它结点,先通知已知的第一个节点,再循环判断接下来的节点
		cur=headlist->next;
		while(getchar()!=10);
		if(sendto(sfd,(&msgbuf),sizeof(msgbuf),0,(struct sockaddr*)&(cur->cin),sizeof(cur->cin))<0)
		{
			ERR_MSG("sendto");
			return -1;
		}

		// 遍历后面的结点,从第二个节点判断,有两种情况,如果是要删除的节点则删除,需要通知的节点只有第一个节点
		// 如果不是要删除的节点则通知该节点用户下线,循环判断第二个节点之后的所有节点是需要通知还是删除
		del = cur->next;	
		for(int i=1;i<headlist->len;i++)
		{
			if(&(del->cin),&(usrline->cin),sizeof(struct sockaddr_in)==0)
			{
				cur->next=del->next;
				headlist->len--;
				free(del);
				del = cur->next;//用于循环判断cur的下一个节点是否为需要删除的节点
				continue;//删除完成后跳过if循环后面的执行,去执行下一次for循环
			}
			else
			{
				//若不是需要删除的节点的话,则需要向该节点发送信息
				if(sendto(sfd,(&msgbuf),sizeof(msgbuf),0,(struct sockaddr*)&(del->cin),sizeof(del->cin))<0)
				{
					ERR_MSG("sendto");
					return -1;
				}
				cur=cur->next;
				del=cur->next;

			}
		}
	}
	pthread_mutex_unlock(&lock);
	return 0;
}

int do_chat(UsrNode *usrline)
{
	UsrNode *cur=headlist->next;
	info msgbuf;
	strcpy(msgbuf.name,usrline->inform.name);
	strcpy(msgbuf.text,usrline->inform.text);

	pthread_mutex_lock(&lock);
	for(int i=0;i<headlist->len;i++,cur=cur->next)//遍历完链表也没有找到客户端退出了循环是没发送的原因,sb while循环
	{
		sleep(1);
		if(memcmp(&(usrline->cin),&(cur->cin),sizeof(struct sockaddr_in))==0)
		{
			continue;
		}

		if(sendto(sfd,(&msgbuf),sizeof(msgbuf),0,(struct sockaddr*)&(cur->cin),sizeof(cur->cin))<0)
		{
			ERR_MSG("sendto");
			return -1;
		}
	}
	pthread_mutex_unlock(&lock);
	return 0;
}

void *callBack1(void *arg)
{
	info rcvbuf;
	ssize_t res;
	struct sockaddr_in cin;
	cin.sin_family = AF_INET;//要指定cin的协议族
	socklen_t size =sizeof(cin);
	memset(&cin,0,sizeof(cin));
	while(1)
	{
		memset(&rcvbuf,0,sizeof(rcvbuf));

		//根据协议类型确定是接收的是登陆消息,转发消息还是下线消息
		if(recvfrom(sfd,&rcvbuf,sizeof(rcvbuf),0,(struct sockaddr*)&cin,&size)<0)
		{
			ERR_MSG("recvfrom");
			return NULL;
		}

		//创建节点使用接收到的客户端信息初始化
		UsrNode *usrline=(UsrNode*)malloc(sizeof(UsrNode));
		usrline->cin=cin;
		usrline->inform=rcvbuf;
		usrline->next=NULL;

		//判断协议的类型,走对应的函数
		switch(rcvbuf.type)
		{
		case 'L':
			//群发给链表中已登入的客户端 保存新的客户端
			do_login(usrline);
			break;
		case 'C':
			do_chat(usrline);
			break;
		case 'Q':
			do_quit(usrline);
			break;
		default:
			printf("协议发送有误\n");
			return NULL;
		}
	}
	pthread_exit(NULL);
}

void *callBack2(void* arg)//还差发送系统信息
{
	info msg; 
	memset(&msg, 0, sizeof(msg));
	strcpy(msg.name,"系统消息");

	while(1)
	{
		scanf("%s",msg.text);
		while(getchar()!=10);

		pthread_mutex_lock(&lock);
		UsrNode *cur=headlist->next;//段错误的地方
		for(int i=0;i<headlist->len;i++,cur=cur->next)
		{	
			if(sendto(sfd,&msg,sizeof(msg),0,(struct sockaddr*)&(cur->cin),sizeof(cur->cin))<0)
			{
				ERR_MSG("sendto");
				return NULL;
			}
		}
		pthread_mutex_unlock(&lock);
	}
	UsrNode *cur=headlist->next;
}

int main(int argc,const char *argv[])
{	
	//创建报式套接字
	sfd=socket(AF_INET,SOCK_DGRAM,0);
	if(sfd<0)
	{
		ERR_MSG("socket");
		return -1;
	}

	//绑定服务器的ip端口号
	struct sockaddr_in sin;
	sin.sin_family = AF_INET;
	sin.sin_port   = htons(SER_PORT);
	sin.sin_addr.s_addr =inet_addr(SER_IP);
	if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)
	{
		ERR_MSG("bind");
		return -1;
	}


	headlist = (UsrList *)malloc(sizeof(UsrList));
	headlist->len=0;
	headlist->next=NULL;
	
	//创建多线程,线程1接收,线程2发送
	pthread_t tid1,tid2;
	if(pthread_create(&tid1,NULL,callBack1,NULL)<0)
	{
		fprintf(stderr,"pthread_create failed\n");
		return -1;
	}

	if(pthread_create(&tid2,NULL,callBack2,NULL)<0)
	{
		fprintf(stderr,"pthread_create failed\n");
		return -1;
	}

	pthread_join(tid1,NULL);
	pthread_cancel(tid2);
	pthread_join(tid2,NULL);
	close(sfd);

	return 0;
}

2.客户端

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

#define ERR_MSG(msg) do{\
	fprintf(stderr,"lien:%d ",__LINE__);\
	perror("msg");\
}while(0)

#define SER_IP "192.168.8.53"
#define SER_PORT 6666

int cfd = 0;

typedef struct msg{
	char type;
	char name[20];
	char text[128];
}info;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; 
typedef struct Node
{
	struct sockaddr_in cin;
	struct msg inform;
	struct Node *next;
}UsrNode;

typedef struct head
{
	int len;
	UsrNode *next; //指向用户链表类型
}UsrList;

//用户名
char username[20]="";


//发送群聊消息
void *callBack1(void *arg)   //void *arg=struct sockaddr_in sin;
{
	//将参数转换回sockaddr_in类型
	struct sockaddr_in sin=*((struct sockaddr_in*)arg);
	info chatbuf;
	memset(&chatbuf, 0, sizeof(chatbuf));
	strcpy(chatbuf.name,username);
	while(1)
	{
		bzero(chatbuf.text,sizeof(chatbuf.text));//像这种循环发送数据包的操作都要清空数组再进行赋值

		//组群聊包
		fgets(chatbuf.text,sizeof(chatbuf),stdin);
		chatbuf.text[strlen(chatbuf.text)-1] = 0;	

		if(strcmp(chatbuf.text,"quit")!=0)
		{
			chatbuf.type='C';
		}
		else
		{
			chatbuf.type='Q';
		}

		//下线条件
		if(sendto(cfd,&chatbuf,sizeof(chatbuf),0,(struct sockaddr*)&sin,sizeof(sin))<0)
		{
			ERR_MSG("sendto");
			return NULL;
		}

		if(strcmp(chatbuf.text,"quit")==0)
		{
			printf("客户端退出\n");
			break;
		}
	}
			pthread_exit(NULL);
}

//接收服务器信息
void *callBack2(void *arg)
{
	struct sockaddr_in sin = *((struct sockaddr_in*)arg);
	ssize_t res=0;

	//接收服务器信息
	info rcvbuf;
	memset(&rcvbuf, 0, sizeof(rcvbuf));
	while(1)
	{
		if(recvfrom(cfd,&rcvbuf,sizeof(rcvbuf),0,NULL,NULL)<0)//为什么要强制转换??
		{
			ERR_MSG("recvfrom");
			return NULL;
		}	
		printf("%s>>>>%s\n",rcvbuf.name,rcvbuf.text);
	}
	pthread_exit(NULL);
}

int main(int argc,const char *argv[])
{	
	//创建报式套接字
	cfd = socket(AF_INET,SOCK_DGRAM,0);
	if(cfd<0)
	{
		ERR_MSG("socket");
		return -1;
	}

	struct sockaddr_in sin;
	sin.sin_family = AF_INET;
	sin.sin_port   = htons(SER_PORT);
	sin.sin_addr.s_addr =inet_addr(SER_IP);

	struct sockaddr_in rcvaddr;

	//快速启用端口
	int reuse = 1;
	setsockopt(cfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
	char buf[128]="";
	ssize_t res=0;

	//登录,组登录包
	info logbuf;

	//将判断条件放入text数组中
	logbuf.type='L';
	printf("请输入用户名>>>>");
	scanf("%s",logbuf.name);
	strcpy(username,logbuf.name);
	while(getchar()!=10);

	if(sendto(cfd,&logbuf,sizeof(logbuf),0,(struct sockaddr*)&sin,sizeof(sin))<0)
	{
		ERR_MSG("sendto");
		return -1;
	}

	//创建多线程,线程1发送,线程2接收
	pthread_t tid1,tid2;
	if(pthread_create(&tid1,NULL,callBack1,(void *)&sin)<0)
	{
		fprintf(stderr,"pthread_create failed\n");
		return -1;
	}

	if(pthread_create(&tid2,NULL,callBack2,(void *)&sin)<0)
	{
		fprintf(stderr,"pthread_create failed\n");
		return -1;
	}

	pthread_join(tid1,NULL);
	pthread_cancel(tid2);
	pthread_join(tid2,NULL);

	close(cfd);

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值