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

问题描述 投票:0回答:1

请指导我为什么阻止函数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] = '\0';
    int bytesReceived;
    if((bytesReceived = recv(sfd, buffer, sizeof(buffer), 0)) == -1)  // Problem starts here
    {
        fprintf(stderr,"Could not retrieve message from client.");
        exit(-5);
    }


c++ c sockets tcp client-server
1个回答
0
投票

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

修复:

if((bytesReceived = recv(connFD, buffer, sizeof(buffer), 0)) == -1)
© www.soinside.com 2019 - 2024. All rights reserved.