网络编程9.3

使用UDP实现多个客户端与服务器的通信,并在使用connect函数后只有一个客户端能与服务器通信

服务器:

#include 
#define SERPORT 9999
#define SERIP "192.168.0.126"
int main(int argc, const char *argv[])
{
	//1、创建旧的套接字
	int oldfd = socket(AF_INET,SOCK_DGRAM,0);
	if(oldfd==-1)
	{
		perror("socket");
		return -1;
	}
	//2、绑定
	struct sockaddr_in sin = {
	.sin_family = AF_INET,
	.sin_port = htons(SERPORT),
	.sin_addr.s_addr = inet_addr(SERIP)};
	if(bind(oldfd,(struct sockaddr *)&sin,sizeof(sin))==-1)
	{
		perror("bind");
		return -1;
	}

	//3、收发信息
	struct sockaddr_in cin;
	socklen_t cinlen = sizeof(cin);
	char buf[100];
	while(1)
	{
		memset(buf,0,sizeof(buf));
		int len = recvfrom(oldfd,buf,sizeof(buf),0,(struct sockaddr *)&cin,&cinlen);
		printf("%s:%d:发来消息\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port));
	printf("服务器接收的消息:%s\n",buf);
	if(strcmp(buf,"aaa")==0)
	{
		connect(oldfd,(struct sockaddr *)&cin,sizeof(cin));
		printf("现在只能与一个客户端通话\n");
	}
		if(len==0)
		{
			printf("客户端跑了\n");
			break;
		}
	}
	close(oldfd);

	return 0;
}

客户端:

#include 
#define CLIPORT 9999
#define CLIIP "192.168.0.126"
int main(int argc, const char *argv[])
{
	//1、创建套接字
	int oldfd = socket(AF_INET,SOCK_DGRAM,0);
	if(oldfd==-1)
	{
		perror("socket");
		return -1;
	}
	struct sockaddr_in cin = {
	.sin_family = AF_INET,
	.sin_port = htons(CLIPORT),
	.sin_addr.s_addr = inet_addr(CLIIP)};
	//2、收发消息
	char buf[1024] = "";
	while(1)
	{
		printf("客户端发消息\n");
		fgets(buf,sizeof(buf),stdin);
		buf[strlen(buf)-1] = '\0';
		sendto(oldfd,buf,sizeof(buf),0,(struct sockaddr *)&cin,sizeof(cin));
		printf("发送成功\n");
		if(strcmp(buf,"quit")==0)
		{
			break;
		}
	}
	close(oldfd);
	return 0;
}

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