1.21 day6 IO网络编程

网络聊天室

服务端

#include 
#define PORT 8888
#define IP "192.168.122.48"
struct MSG
{
	char tyep;
	char name[20];
	char buf[128];
};
typedef struct Node
{
	struct sockaddr_in cin;
	struct Node*next;
}*node;

int main(int argc, const char *argv[])
{
	node head=NULL;
	int sfd=socket(AF_INET,SOCK_DGRAM,0);
	if(sfd==-1)
	{
		perror("socket error");
		return -1;
	}
	int reuse=setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));
	if(reuse==-1)
	{
		perror("setsockopt error");
		return -1;
	}
	struct sockaddr_in sin;
	sin.sin_family=AF_INET;
	sin.sin_port=htons(PORT);
	sin.sin_addr.s_addr=inet_addr(IP);
	if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
	{
		perror("bind error");
		return -1;
	}
	int pid=fork();
	if(pid>0)
	{
		//父收
		struct sockaddr_in cin;
		socklen_t socklen=sizeof(cin);
		struct MSG mg;
		node p=(node)malloc(sizeof(struct Node));
		p->next=NULL;
		while(1)
		{
			bzero(&mg,sizeof(mg));
			recvfrom(sfd,&mg,sizeof(mg),0,(struct sockaddr*)&cin,&socklen);
			int tyep=ntohl(mg.tyep);
			switch(tyep)
			{
			case 'L':
				{
					printf("%s[%s:%d]登陆成功\n",mg.name,inet_ntoa(cin.sin_addr),ntohs(cin.sin_port));
					sprintf(mg.buf,"----%s登陆成功----",mg.name);
					while(p->next!=NULL)
					{
						p=p->next;
						sendto(sfd,&mg,sizeof(mg),0,(struct sockaddr*)&(p->cin),sizeof(p->cin));
					}
					p->cin=cin;
					p->next=NULL;
					head->next=p;

				}
				break;
			case 'C':
				{
					//便利链表但是要跳过当前客户端
					char wbuf[258]="";
					sprintf(wbuf,"%s:%s",mg.name,mg.buf);
					strcpy(mg.buf,wbuf);
					while(p->next!=NULL)
					{
						p=p->next;
						if(memcmp(&cin,&p->cin,sizeof(cin))!=0)
						{
							sendto(sfd,&mg,sizeof(mg),0,(struct sockaddr*)&(p->cin),sizeof(p->cin));
						}
					}
				}
				break;
			case 'Q':
				{
					//暗元素删除
					sprintf(mg.buf,"----%s已下线----",mg.name);
					while(p->next!=NULL)
					{
						if(memcmp(&cin,&p->next->cin,sizeof(cin))==0)
						{
							node q=p->next;
							p->next=q->next;
							free(q);
						}else
						{
							p=p->next;
							sendto(sfd,&mg,sizeof(mg),0,(struct sockaddr*)&p->cin,sizeof(p->cin));
						}
					}
				}
				break;
			}
		}

	}else if(pid==0)
	{
		//子发
		struct MSG mg={htonl(1),"系统"};
		while(1)
		{
			bzero(mg.buf,128);
			fgets(mg.buf,128,stdin);
			mg.buf[strlen(mg.buf)-1]=0;
			sendto(sfd,&mg,sizeof(mg),0,(struct sockaddr*)&sin,sizeof(sin));
		}

	}else
	{
		perror("fork error");
		return -1;
	}


	return 0;
}

客户端

你可能感兴趣的:(网络)