C,TCP,recvAll块没有正在接收任何内容

时间:2017-06-23 19:07:42

标签: c sockets tcp recv

我是C和套接字编程的新手,所以请耐心等待。以下代码主要来自Beej网络指南,并进行了一些更改。我附加了接收器代码(在这种情况下是TCP服务器),它侦听多个TCP连接。我有一个发送器(客户端)不断向这个接收器发送固定的数据块。这段代码(我清理并删除了一些与我的问题无关的函数定义)如果不调用recv_all函数,我只调用recv()。但问题是我需要对每个接收数据块进行处理,所以我需要整个块。所以我认为我应该使用recv_all()。

现在问题是它在recv_all()中陷入了无限循环,因为n总是为0.我非常感谢你的帮助。

#define PORT "3490"  // the port users will be connecting to
#define BACKLOG 20     // how many pending connections queue will hold
#define MAXDATASIZE 801 // max number of bytes we can get at once 

int recv_all(int socket, char *buffer, int *length)
{
    int total = 0;        // how many bytes we've sent
    int bytesleft = *length; // how many we have left to send
    int n;

    while(total < *length) {

        n = recv(socket, buffer+total, bytesleft, 0);
        if (n == -1) { break; }
        total += n;
        bytesleft -= n;
    }
    *length = total; // return number actually received here

    return n==-1?-1:0; // return -1 on failure, 0 on success
}

int main(void)
{
    int sockfd, new_fd;  // listen on sock_fd, new connection on new_fd
    struct addrinfo hints, *servinfo, *p;
    struct sockaddr_storage their_addr; // connector's address information
    socklen_t sin_size;
    struct sigaction sa;
    int yes=1;
    char s[INET6_ADDRSTRLEN];
    int rv;
    double buf[MAXDATASIZE];
    int lenRecv;

    struct sockaddr_in local_addr;      // For the new addition to bind it to an interface

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE; // use my IP

    if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }

    // loop through all the results and bind to the first we can
    for(p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
            perror("server: socket");
            continue;
        }

        if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
            perror("setsockopt");
            exit(1);
        }

        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("server: bind");
            continue;
        }
        break;
    }

    freeaddrinfo(servinfo); // all done with this structure

    if (listen(sockfd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }

    sa.sa_handler = sigchld_handler; // reap all dead processes
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        perror("sigaction");
        exit(1);
    }

    printf("server: waiting for connections...\n");

    while(1) {  // main accept() loop
        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()) { // this is the child process
            close(sockfd); // child doesn't need the listener

            for (int i=0; i<1000000; i++) {
                int rowInfoSize;
                //if ((numbytes = recv(sockfd, buf, sizeof (buf), 0)) == -1) {
                //if ((numbytes = recv(new_fd, buf, sizeof (buf), MSG_WAITALL)) == -1) {        // I THINK THE BETTER WAY IS to CHECK THE OUTPUT AND LOOP UNTIL COMPLETE.               

                lenRecv = sizeof (buf);
                //if (recv_all(new_fd, (char *)buf, &lenRecv) == -1) {
                if (recv_all(new_fd, buf, &lenRecv) == -1) {
                    perror("sendall");
                    printf("We only sent %d bytes because of the error!\n", lenRecv);
                } 
            }   
            close(new_fd);
            exit(0);
        }
        close(new_fd);  // parent doesn't need this
    }
    return 0;
}

2 个答案:

答案 0 :(得分:0)

你忽略了流的结束。如果n == 0对等方已断开连接。你的代码将永远循环。

将其全部丢弃并使用recv()选项{。}}。

答案 1 :(得分:-1)

给recv_all一个超时值

int recv_all(int socket, char *buffer, int *length, int timeout)

并在recv()之前使用select

int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
  

看起来像这样

int recv_all(int socket, char *buffer, int *length)
{
    int total = 0;        // how many bytes we've sent
    int bytesleft = *length; // how many we have left to send
    int n = -1;

    struct timeval timeout;
    fd_set rset;
    int rc;

    timeout.tv_sec = 1;
    timeout.tv_usec = 0;

    while(total < *length) {

        FD_ZERO(&rset);
        FD_SET(socket, &rset);
        rc = select(socket + 1, &rset, NULL, NULL, &timeout);
        if(rc < 0)
        {
            // errno
            n = -1;
            break;
        }

        if(0 == rc)
        {
            // timeout
            n = -1;
            break;
        }

        if(FD_ISSET(socket, &rset))
        {
            n = recv(socket, buffer+total, bytesleft, 0);
            if (n == -1) { break; }
            total += n;
            bytesleft -= n;
            timeout.tv_sec = 1;
            timeout.tv_usec = 0;
        }
    }

    *length = total; // return number actually received here

    return n==-1?-1:0; // return -1 on failure, 0 on success
}