簡體   English   中英

為什么將TCP數據包發送到本地主機需要這么長時間?

[英]Why does it take so long to send TCP packets to localhost?

我寫了一個簡單的C ++客戶/服務器對。 服務器只是在套接字接受上派生一個進程,然后等待來自客戶端的數據包,然后以另一個數據包進行響應。 客戶端只是向服務器發送一個數據包,然后等待答復。 在發送之前和接收之后,我在客戶端中都有計時代碼。

我在本地計算機上同時運行服務器和客戶端,並將客戶端連接到本地主機。

在我看來,延遲的中位數似乎是2毫秒左右。 鑒於我實際上並沒有在網絡上發送任何內容。 2毫秒的延遲對我來說似乎太高了。

誰能解釋為什么我看到這么高的延遲,或者對於環回地址來說,這樣的時間是否現實?

我在Linux Ubuntu 12.04上。 我直接使用TCP套接字系統調用,而不是使用任何包裝程序(即,接受,監聽,發送,接收)。

服務器主體:

while (1) 
{   
    ++msgNum;

    sin_size = sizeof their_addr; 
    new_fd = accept(sockfd, (struct sockaddr*) &their_addr, &sin_size);
    if (new_fd == -1) 
    {   
        perror("accept");
        continue; 
    }   

    inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr*) &their_addr), 
        s, sizeof s); 
    printf("server: got connection from %s\n", s); 

    if (!fork())
    {   
        close(sockfd); // child doesn't need the listener

        MyMsg msg;
        strcpy(msg.buf, "Hello world");

        for (int i = 1; i <= NUM_TEST_MSGS; ++i)
        {   
            msg.id = i;

            int numbytes = 0;
            int bytesRecv = 0;

            while (numbytes < MSG_LEN)
            {   
                int sendSize = MSG_LEN - numbytes;
                if ((bytesRecv = send(new_fd, ((char*) &msg) + numbytes, 
                        sendSize, 0)) == -1) 
                {   
                    perror("send");
                    exit(1);
                }   
                numbytes += bytesRecv;
            }   

            assert(numbytes == MSG_LEN);

            //printf("Server sent %d num bytes\n", numbytes);
        }   

        printf("Server finished sending msgs.\n");

        close(new_fd);
        exit(0);
    }   
    close(new_fd);
} 

客戶團體:

for (int i = 1; i <= NUM_TEST_MSGS; ++i)
{
    MyMsg msg;

    int numbytes = 0;
    int bytesRecv = 0;

    int start = rdTsc.Rdtsc();

    while (numbytes < MSG_LEN)
    {
        int recvSize = MSG_LEN - numbytes;
        if ((bytesRecv = recv(sockfd, ((char*) &msg) + numbytes, recvSize, 0)) == -1)
        {
            perror("recv");
            exit(1);
        }

        numbytes += bytesRecv;
    }

    int end = rdTsc.Rdtsc();

    perfCounter.Track(end - start);

    if (numbytes != MSG_LEN)
    {
        printf("COMP FAILED: %d %d\n", numbytes, MSG_LEN);
    }

    assert(numbytes == MSG_LEN);

    if (i != msg.id)
    {
        printf("Msg %d id %d \n", i, msg.id);
    }

    //if (numbytes != MSG_LEN) printf("GOT WEIRD SIZE %d\n", numbytes);
    assert(msg.id == i);

    //printf("client: received %d num bytes id %d body '%s'\n", numbytes, msg.id, msg.buf);

    if (i % 1000 == 0)
    {
        printf("Client: Received %d num msgs.\n", i);
    }
}

printf("Client: Finished successfully.\n");

close(sockfd);

對於可能甚至從未離開內核緩沖區的內容,2ms當然聽起來很高。 我懷疑用於時間戳的功能實際上可能不正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM