2016-04-11 45 views
2

我開始使用AIO寫一個簡單的客戶端服務器program.My客戶端程序:aio_write並不在我簡單的客戶端/服務器proggram工作

int main(int argc, char const *argv[]) 
{ 

    int port = 6000; 
    struct sockaddr_in my_address; 
    memset(&my_address, 0, sizeof(my_address)); 
    my_address.sin_family = AF_INET; 
    my_address.sin_addr.s_addr = htonl(0x7f000001); // 127.0.0.1 
    my_address.sin_port = htons(port); 

    int fd = socket(AF_INET, SOCK_STREAM, 0); 

    connect(fd, (struct sockaddr*)&my_address, sizeof(my_address)); 

    char * str = "hello"; 

    struct aiocb my_aio; 
    memset((void*)&my_aio, 0, sizeof(struct aiocb)); 
    my_aio.aio_fildes = fd; 
    my_aio.aio_buf = str; 
    my_aio.aio_nbytes = strlen(str); 
    aio_write(&my_aio); 
    return 0; 
} 

我的服務器程序:

int main(int argc, char *argv[]) 
{ 
    int sockfd, newsockfd, portno, clilen; 
    char buffer[256]; 
    struct sockaddr_in serv_addr, cli_addr; 
    int n; 
    if (argc < 2) { 
     fprintf(stderr,"ERROR, no port provided\n"); 
    } 
    sockfd = socket(AF_INET, SOCK_STREAM, 0); 
    if (sockfd < 0) 
     error("ERROR opening socket"); 
    bzero((char *) &serv_addr, sizeof(serv_addr)); 
    portno = atoi(argv[1]); 
    serv_addr.sin_family = AF_INET; 
    serv_addr.sin_addr.s_addr = INADDR_ANY; 
    serv_addr.sin_port = htons(portno); 
    if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) 
     error("ERROR on binding"); 

    listen(sockfd,5); 
    clilen = sizeof(cli_addr); 
    newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); 
    sleep(5); 
    bzero(buffer,256); 
    n = read(newsockfd,buffer,255); 
    if (n < 0) error("ERROR reading from socket"); 
    printf("Here is the message: %s\n",buffer); 

    return 0; 
} 

我希望我的服務器端打印出你好,但它不。提前致謝。

回答

1

否則您的代碼有效,但在異步寫入完成之前退出main;因此套接字在完成異步寫入之前關閉。我儘可能少地在aio_write調用之後添加一個perror("aio_write")以找出它給出的錯誤(如果有),現在hello已成功發送到服務器。

您可能想要使用aio_suspend以確保任何未完成的操作在退出main之前完成。

相關問題