某些UDP数据包不会到达目标C ++

时间:2013-12-01 21:32:33

标签: c++ udp

我必须测试两个Amazon EC2实例之间的TCP和UDP连接。目前我正试图从一个实例到它自己进行测试,这是在localhost中。我写了一个C ++程序来做到这一点。 它与TCP完美配合,它达到600-900 MB / s,我认为它太高但我也认为我的计算是正确的。 问题出在UDP测试中。 我的客户端发送1024 B的数据包,直到它发送了256 KB,我的服务器等待数据包,直到它收到256 KB。我必须测量接收256 KB的时间,所以我这样做了10次以获得平均时间。这是代码片段:

服务器

    char buffer[256*1024];
    memset(&buffer, 0, sizeof buffer);
    for (int i = 0; i < 10; i++) {
        int rcvd = 0;
        while(rcvd < 256*1024) {
            rcvd += recvfrom(socket, (void *) &buffer, sizeof(buffer), 0, &addr, &fromlen);
        }
        printf("rcvd = %d\n", rcvd);
    }

客户端

    char buffer[1024];
    memset(&buffer, 1, sizeof buffer);
    for (int i = 0; i < 10; i++) {
        int sent = 0;
        while(sent < 256*1024) {
            sent += sendto(sock, buffer, sizeof (&buffer), 0, (struct sockaddr *)&server, slen);
        }
        cout << sent << " Bytes sent." << endl;     
    }

客户端在每次迭代中发送一​​个1024字节的数据包,直到它发送了256 KB为止;并且服务器在每次迭代中等待256 KB的数据包。 在最后一次迭代中,服务器似乎得到大约180000字节(256 KB = 262144字节),因此有些数据包会丢失。 知道为什么会这样吗? 谢谢!

编辑:

我试图检测 Martin James 建议的任何错误。代码现在就像:

服务器

    for (int i = 0; i < 10; i++) {
    timestamp_t ini = get_timestamp();
    int rcvd = 0;
    int res = 0;
    while(rcvd < 256*1024) {
        rcvd += recvfrom(socket, (void *) &buffer, sizeof(buffer), 0, &addr, &fromlen);
        if (res == -1 ){
            printf("Oh dear, something went wrong with read()! %s\n", strerror(errno));
            sleep(5);
        }
        else{
            rcvd += res;
        }
    }

客户端

for (int i = 0; i < 10; i++) {
        int sent = 0;
        int res = 0;
        while(sent < 256*1024) {
            res = sendto(sock, buffer, sizeof (&buffer), 0, (struct sockaddr *)&server, slen);
            if (res == -1 ){
                printf("Oh dear, something went wrong with read()! %s\n", strerror(errno));
                sleep(5);
            }
            else{
                sent += res;
            }
        }
        cout << sent << " Bytes sent." << endl;

    }

但是,在任何尝试中都没有检测到错误。 前三次测试成功。这是,客户端发送256 KB 10次,服务器接收256 KB 10次。然后,在第四次尝试时,服务器未收到所有数据。我又试了一次,虽然也许管道在那个港口有点崩溃了。所以然后我多次更改端口,但是服务器不再接收整个数据,因此它停留在while循环上等待完成最后的256 KB块。 UDP数据包从localhost丢失到localhost?这是什么原因? 谢谢大家的回复。

0 个答案:

没有答案