1

我正在尝试制作 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;
}
4

1 回答 1

2

您正在弄乱client_addr对象:

recvfrom(....,(struct sockaddr *)&client_addr,(socklen_t *)&client_addr);
                                                            ^^^^^

尝试类似:

socklen_t len = sizeof(client_addr);
recvfrom(..., (struct sockaddr *)&client_addr, &len);
于 2013-10-03T12:50:03.827 回答