我正在尝试创建一个UDP客户端/服务器..服务器从客户端接收消息但客户端没有到达服务器消息..请指导我
服务器:
int main()
{
char message[100];
int sockfd, newsockfd;
struct sockaddr_in my_addr, client_addr;
sockfd=socket(AF_INET, SOCK_DGRAM, 0);
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(1025);
my_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
memset(&(my_addr.sin_zero),'\0',8);
bind(sockfd,(struct sockaddr*)&my_addr,sizeof(my_addr));
perror("bind");
while(1)
{
for(int i=0;i<100;i++)
message[i]=0;
do{
cout<<"Waiting..!!"<<endl;
recvfrom(sockfd,message,sizeof(message),0,(struct sockaddr *)&client_addr,(socklen_t *)&client_addr); // receiving messages to client
cout<<"CLIENT : "<<message<<endl;
cin.getline(message,100);
sendto(sockfd,message,sizeof(message),0,(struct sockaddr *)&client_addr,sizeof(client_addr)); // sending messages to client
}while(strcmp(message,"quit")!=0);
}
close(sockfd);
return 0;
}
这是它正确运行的客户端部分,但是没有从服务器接收消息,并且每件事都运行良好
客户:
int main()
{
int sockfd;
struct sockaddr_in my_addr;
sockfd=socket(AF_INET, SOCK_DGRAM, 0);
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(1025);
my_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
char buffer[100];
do{
cout<<"CLIENT : ";
cin.getline(buffer,100);
sendto(sockfd,buffer,sizeof(buffer),0,(struct sockaddr *) &my_addr,sizeof(my_addr)); // sending messages to server
recvfrom(sockfd,buffer,sizeof(buffer),0,(struct sockaddr *)&my_addr,(socklen_t *)&my_addr); // receiving messages to server
cout<<"SERVER : "<<buffer<<endl;
}while(strcmp(buffer,"quit")!=0);
close(sockfd);
perror("connection");
return 0;
}
答案 0 :(得分:2)
你弄乱了client_addr
对象:
recvfrom(....,(struct sockaddr *)&client_addr,(socklen_t *)&client_addr);
^^^^^
尝试类似:
socklen_t len = sizeof(client_addr);
recvfrom(..., (struct sockaddr *)&client_addr, &len);