0

我正在尝试制作一个异步 UDP 聊天应用程序,目前只有一个客户端和服务器。

当我运行我的服务器时,会显示很多冗余数据。之后,当输入一些文本时,

发送文件时出错!

被展示。

有人可以看看代码,让我知道我哪里出错了吗?

服务器:
u_long iMode=1;ioctlsocket(sd,FIONBIO,&iMode); 诠释n=sd+1;

fd_set readfds,writefds;
while(1)
{
    FD_ZERO(&readfds);
    FD_ZERO(&writefds);
    FD_SET(sd,&readfds);
    FD_SET(sd,&writefds);

    int rv = select(n, &readfds, &writefds, NULL, NULL);
    if(rv==-1)
    {
        printf("Error in Select!!!\n");
        exit(0);
    }
    if(rv==0)
    {
        printf("Timeout occurred\n");
    }
    if (FD_ISSET(sd, &readfds))
    {
        FD_CLR(sd,&readfds);
        int client_length = (int)sizeof(struct sockaddr_in);
        memset(&buffer,0,sizeof(buffer));
        int bytes_received = recvfrom(sd, buffer,SIZE, 0, (struct sockaddr *)&client, &client_length);
        if (bytes_received < 0)
        {
            fprintf(stderr, "Could not receive datagram.\n");
            closesocket(sd);
            WSACleanup();
            exit(0);
        }
    }

    printf("\nClient says: %s",buffer);
    printf("\nWrite :");

    fgets(buffer,SIZE,stdin);
    if(FD_ISSET(sd,&writefds))
    {
        FD_CLR(sd,&writefds);
        int client_length = (int)sizeof(struct sockaddr_in);
        if(sendto(sd, buffer,strlen(buffer), 0, (struct sockaddr *) &client,client_length)<0)
        {
            printf("Error sending the file! \n");
            exit(1);
        }
    }
}
closesocket(sd);
WSACleanup();

return 0;
}
4

1 回答 1

1

我看到一个问题。这一行:

int rv = select(n, &readfds, &writefds, NULL, NULL);

几乎总是会在 readfds 为空的情况下立即返回。但是 writefds 几乎总是用“sd”套接字设置,表明它已准备好写入/发送。

因此,您的代码正确地跳过了调用 recvfrom() 的尝试,但没有什么能阻止它落入发送代码路径。所有变量,如 client、client_length 和 buffer,在那时可能都未初始化。或者更糟的是,缓冲区和客户端正是循环中最后一次成功调用时的样子。这可能解释了冗余数据。

我的建议是根本不要在 select 调用中设置“writefds”。然后仅在您实际阅读时“发送”。无论如何, sendto 调用都不会阻塞很长时间。

于 2013-04-16T10:14:21.820 回答