在C中请求套接字上的数据

在C中请求套接字上的数据,c,sockets,C,Sockets,在我的C应用程序中,我以以下方式等待套接字上的数据: printf("Opening socket and wait for data.\n"); while (i < 5) while((connection_fd = accept(socket_fd, (struct sockaddr *) &address, &address_length))

在我的C应用程序中,我以以下方式等待套接字上的数据:

printf("Opening socket and wait for data.\n");
while (i < 5)  
   while((connection_fd = accept(socket_fd, 
                            (struct sockaddr *) &address,
                            &address_length)) > -1)
   {
    bzero(buffer, 64);
    n = read(connection_fd,buffer,64);
    if (n < 0) printf("ERROR reading from socket");
    printf("Here is the message of length %d bytes:\n\n", n);
    for (int i = 0; i < n; i++)
    {
      printf("%02X", buffer[i]);
    } 
    printf("\n\n");          
    break;  
    }
 i++
 }
这意味着我从套接字读取了5次数据,但是,从外观上看,我似乎打开了5个不同的连接,对吗?是否可以只打开一次连接,使其保持活动状态,然后检查此连接上是否有可用数据

谢谢你,帕特里克

当然。 为此,您可能希望将参数交换到两个while循环:


对。当我它很简单时,就把它去掉。将调用accept函数的语句移到循环之外,然后使用相同的套接字描述符调用read。

您的代码需要重新构造,您应该只为每个新连接接受一次:

while (1) {
    connection_fd = accept(socket_fd, ...);

    /* check for errors */
    if (connection_fd < 0) {
      /* handle error */
    }

    /* note this could block, if you don't want
       that use non-blocking I/O and select */    
    while ((n=read(connection_fd, buf, ...)) > 0) {
        /* do some work */
    }

    /* close fd */ 
    close(fd);
}
你为什么要这样做?要么中断;循环或继续;用于新连接

while (1) {
    connection_fd = accept(socket_fd, ...);

    /* check for errors */
    if (connection_fd < 0) {
      /* handle error */
    }

    /* note this could block, if you don't want
       that use non-blocking I/O and select */    
    while ((n=read(connection_fd, buf, ...)) > 0) {
        /* do some work */
    }

    /* close fd */ 
    close(fd);
}
if (n < 0) printf("ERROR reading from socket");