本文主要是介绍网络编程9.3,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用UDP实现多个客户端与服务器的通信,并在使用connect函数后只有一个客户端能与服务器通信
服务器:
#include <myhead.h>
#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 <myhead.h>
#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;
}
这篇关于网络编程9.3的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!