recvfrom 在进入等待状态后只收到很少的数据包

recvfrom only receive few packets after that it goes in waiting state

您好,我是 Socket 编程的新手,我尝试创建一个客户端服务器应用程序,其中我的服务器是相机,我的 C++ 应用程序中是客户端。 当我看到计算机和相机之间的数据包传输时,它显示相机在停止后发送了超过 150000 个数据包。但是当我收到我能够在 400 - 450 packets 之后的某个时间接收 recvfrom 函数进入等待状态。如果我在不停止前一个文件的情况下再次 运行 该 exe 文件,它将再次收到 400-450 packets.

接收数据包的代码

SOCKET out1 = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
    if (out1 == INVALID_SOCKET)
    {
        cout << out1 << endl;
    }
    server.sin_family = AF_INET;
    server.sin_port = htons(3956);
    inet_pton(AF_INET, "192.168.1.140", &server.sin_addr);
    int serverLength = sizeof(server);

    connect(out1, (sockaddr*)&server, serverLength);
    while (1)
    {
        memset(buf, 0, sizeof(buf));
        int bytesIn = recvfrom(out1, buf, 1444, 0, (sockaddr*)&server, &serverLength);
        if (bytesIn > 0)
        {
            cout << "Image Received :" << bytesIn <<packet_counter << endl;
            packet_counter++;
        }
        else
        {
            cout << "Not Received : " << endl;
        }
    }

我运行正在使用管理员权限安装 .exe。

谁能告诉我为什么 recvfrom 函数会进入等待状态。

提前致谢。

编辑:-

抱歉,我提供了完整的代码。

  #include <stdio.h>
#include <Windows.h>
#include <thread>
#include <WinSock2.h>

// Library
#pragma comment(lib, "ws2_32.lib")

using namespace std;

//***** Function Decleration *****//
void _packetConfig(SOCKET);
void _sendPacket(SOCKET, const char*, int, int);

// Global Variable
sockaddr_in server;

//***** Main Function *****//
void main(char argc, char* argv[])
{
    WSADATA data;
    WORD version = MAKEWORD(2, 2);
    if(WSAStartup(version, &data) == SOCKET_ERROR)
    {
        cout << "Can't Start Socket" << WSAGetLastError<<endl;
        return;
    }
    char buf[2000];

        SOCKET out1 = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
        if (out1 == INVALID_SOCKET)
        {
            cout << out1 << endl;
        }
        server.sin_family = AF_INET;
        server.sin_port = htons(3956);
        inet_pton(AF_INET, "192.168.1.140", &server.sin_addr);
        int serverLength = sizeof(server);

        connect(out1, (sockaddr*)&server, serverLength);


        int packet_counter = 0;


        SOCKET out = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

        _packetConfig(out);

        cout << "Inside Main" << endl;
        while (1)
        {
            //connect(out1, (sockaddr*)&server, serverLength);
            memset(buf, 0, sizeof(buf));
            int bytesIn = recvfrom(out1, buf, 1444, 0, (sockaddr*)&server, &serverLength);
            if (bytesIn > 0)
            {
                cout << "Image Received :" << bytesIn <<packet_counter << endl;
                packet_counter++;
            }
            else
            {
                cout << "Not Received : " << endl;
            }
        }

        WSACleanup();
}

//***** Function to Send Bytes to the Camera *****//
void _sendPacket(SOCKET sock, const char* s, int len, int i)
{
    int sendOk = sendto(sock, (const char*)s, len, 0, (sockaddr*)&server, sizeof(server));

    if (sendOk == SOCKET_ERROR)
    {
        cout << "Didn't Work" << WSAGetLastError() << endl;
    }
    else
    {
        cout << "\nSend Succesfully" << " " << i << endl;
    }
    char buf[2000];
    int serverLength = sizeof(server);
    int bytesIn = recvfrom(sock, buf, 2000, 0, (sockaddr*)&server, &serverLength);
    if (bytesIn > 0)
    {
        cout << "Message Received :" << bytesIn << endl;
    }
}

//***** Function to call the _sendPacket function and send commands to the Camera *****//
void _packetConfig(SOCKET sock)
{
    // 59 Commands and every command call _snedPacket function to send commands to camera  it will working properly
}

在上面的代码中,我必须先发送这个 59 commands 写在 _packetConfig 函数中,然后只有相机会发送 Image packets 我正在接收所有命令的回复。

当我 运行 wireshark 也使用该代码时,我可以看到在这 59 个命令之后 相机给出 3580*51 packets.i.e 51 帧,每帧包含 3580 个数据包

感谢您 post 使用您的代码。它实际上有一些问题,所以首先我将 post 一些代码作为参考,然后提及我在之后发现的主要问题。

好的,这是一些适合我的代码:

#include <WinSock2.h>                   // ** before** windows.h
#include <WS2tcpip.h>
#include <iostream>
#include <stdio.h>
#include <Windows.h>
#include <assert.h>

#pragma comment (lib, "ws2_32.lib")

const int port = 3956;

// main
int main (char argc, char* argv[])
{
    WSADATA wsadata;
    WORD version = MAKEWORD(2, 2);

    int err = WSAStartup (MAKEWORD (2, 2), &wsadata);
    if (err)
    {
        std::cout << "WSAStartup failed, error: " << err << std::endl;
        return 255;
    }

    char buf [1444];
    bool send = argc > 1 && _stricmp (argv [1], "send") == 0;

    if (send)
    {
        // Send
        SOCKET skt_out = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        assert (skt_out != INVALID_SOCKET);

        sockaddr_in destination_address = { };
        destination_address.sin_family = AF_INET;
        destination_address.sin_port = htons (port);
        inet_pton (AF_INET, "192.168.1.2", &destination_address.sin_addr);
        memset (buf, 'Q', sizeof (buf));
        printf ("Sending: ");

        for ( ; ; )
        {
            sendto (skt_out, buf, sizeof (buf), 0, (const sockaddr *) &destination_address, sizeof (destination_address));
            printf (".");
            Sleep (50);
        }

        closesocket (skt_out);
        WSACleanup ();
        return 0;
    }

    // Receive
    SOCKET skt_in = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    assert (skt_in != INVALID_SOCKET);

    int receive_buffer_size = 65536;
    if ((setsockopt (skt_in, SOL_SOCKET, SO_RCVBUF, (const char *) &receive_buffer_size, sizeof (int)) ) < 0)
        std::cout << "Could not set SO_RCVBUF, error: " << WSAGetLastError () << std::endl;

    sockaddr_in receive_address = { };
    receive_address.sin_family = AF_INET;
    receive_address.sin_port = htons (port);
    receive_address.sin_addr.s_addr = htonl (INADDR_ANY);

    if (bind (skt_in, (const sockaddr *) &receive_address, sizeof (receive_address)) == -1)
    {
        std::cout << "bind failed , error: " << WSAGetLastError () << std::endl;
        return 255;
    }

    int packetCounter = 0;
    printf ("Receiving: ");

    for ( ; ; )
    {
        int bytesIn = recvfrom (skt_in, buf, sizeof (buf), 0, NULL, 0);
        if (bytesIn > 0)
            std::cout << "Packet received:" << bytesIn << " bytes (" << ++packetCounter << ")" << std::endl;
        else
            std::cout << "Receive error: " << WSAGetLastError () << std::endl;
    }

    closesocket (skt_in);
    WSACleanup ();
    return 0;
}

要运行 在'send' 模式下,指定send 作为命令行的第一个参数。否则它充当接收器(又名服务器)。

那么你的代码有什么问题?嗯,排名不分先后:

  • 正如我们已经说过的,您不应该使用 SOCK_RAW
  • 您需要在接收套接字上调用 bind 以便它知道要侦听的端口。 recvfromsockaddr *from 参数并不代表您认为的意思(请检查 docs)。你会看到我将其作为 NULL 传递。
  • 您误解了 WSAStartup 中的 return 值。再次,请检查文档。

但是说了这么多,本质上是您错过了对 bind 的调用。我重写了代码,因为你的代码比较乱

另外,重要的细节,UDP 不保证送达 - 有很多原因导致已发送的数据包未收到或什至可能收到乱序(您的相机是否对数据包进行排序某种方式?)
您需要在应用程序的逻辑中满足这一点(这是一个问题,最好使用 TCP,它可以保证数据包的传递和排序)。