TCP 套接字(客户端-服务器)recv() 返回 -1 值

TCP sockets (client-server) recv() returning -1 value

请指导我为什么阻塞函数 recv() 不等待来自客户端的消息。相反,它返回值 -1。请指导我如何解决这个问题。

服务器代码(部分):

    (call to getaddrinfo) // struct addrinfo hints, *res

    int sfd = socket(res->ai_family, res->ai_socktype,res->ai_protocol);
    if(sfd == -1)
    {
        printf("Socket creation failed .....");
        exit(-3);
    }
    fcntl(sfd, F_SETFL, ~O_NONBLOCK);

    if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0)
    {
        herror("setsockopt(SO_REUSEADDR) failed");
    }

    bind(sfd,res->ai_addr, res->ai_addrlen);
    if(listen(sfd, BACKLOG)!=0)
    {
        printf("Listen Error");
        exit(-4);
    }
    printf("\n\nListening on port: %s\n\n", argv[1]);
    struct sockaddr_storage clientAddr;
    socklen_t addrSize = sizeof(clientAddr);
    int connFD = accept(sfd,(struct sockaddr*)&clientAddr, &addrSize); // connection successful
    char buffer[10] = "Hello!";
    write(connFD, buffer, sizeof(buffer)); // message sent to client
    buffer[0] = '[=10=]';
    int bytesReceived;
    if((bytesReceived = recv(sfd, buffer, sizeof(buffer), 0)) == -1)  // Problem starts here
    {
        fprintf(stderr,"Could not retrieve message from client.");
        exit(-5);
    }


问题是您在错误的套接字 (sfd) 上调用 recv 应该是 (connFD)

修复:

if((bytesReceived = recv(connFD, buffer, sizeof(buffer), 0)) == -1)