为什么recv()会挂起?

时间:2017-10-01 06:50:08

标签: sockets tcp ip

我现在使用套接字编程,过程如下:

  

客户端-------从scanf()获取用户名------发送   用户名---------服务器

     

服务器-------发送确认消息-------客户端

     

客户端------获取确认-----从scanf()获取密码------发送密码----------服务器

     

服务器-------获取密码

但是我在第二个recv()得到服务器挂起,我用Google搜索它,唯一的答案是读取边界问题,但对于用户名,我确实告诉服务器它应该得到多少字节...可以&#39关于什么'继续...

代码客户端:

    printf("Please enter the username: ");

    scanf("%s", username); 

    //send username

    datalen = strlen(username);

    temp = htonl(datalen);   

    send(simpleSocket, (char*)&temp, sizeof(datalen),0); 

    bytes_sent = send(simpleSocket, (char*)&username, datalen,0);

    //waiting acknowledge
    bytes_recv = recv(simpleSocket, (char*)&acknowledge,sizeof(acknowledge), 0);    

    if(bytes_recv > 0){
        printf("Got Acknowledge!\n");
    }
    else{
        printf("Didn't Get Acknowledge!\n");
    }

    //if get acknowledge, get password
    if(bytes_recv > 0){

    printf("Please enter the password: ");        
    scanf("%s", password);

    //send password
    datalen = strlen(password);
    temp = htonl(datalen);
    bytes_sent = send(simpleSocket, (char*)&temp, sizeof(datalen),0); 

    bytes_sent = send(simpleSocket, (char*)&password, datalen, 0);
    printf("Bytes_sent(password): %d\n", bytes_sent);
}

代码服务器:

int buflen = 0;

bytes_recv = recv(simpleChildSocket, (char*)&buflen, sizeof(int), 0);

buflen = ntohl(buflen);

//printf("%d\n", buflen);

bytes_recv = recv(simpleChildSocket, username, buflen, 0);

if(bytes_recv > 0){

    printf("Sent Acknowledge!\n");
    char acknowledge[256] = "Have Gotten Username!";  
    bytes_sent = send(simpleChildSocket, acknowledge,strlen(acknowledge),0);

    index = CheckUsername(username);
    printf("Index at: %d\n", index);

}

else{
    printf("Didn't receive username!\n");
    close(simpleChildSocket);
}



//read password

bytes_recv = recv(simpleChildSocket, (char*)&buflen, sizeof(int), 0);

buflen = ntohl(buflen);

bytes_recv = recv(simpleSocket, password, buflen, 0);

if(bytes_recv > 0){

    printf("Bytes_recv(password): %d\n", bytes_recv);

    if(password == PASSWORD[index]){

        printf("Match Success!\n");

    }

}

else{

    printf("Didn't Get Password!");

    close(simpleChildSocket);

}

1 个答案:

答案 0 :(得分:0)

您假设一个发送等于一个接收,并且每个接收都填充所提供的缓冲区。不一定如此。请参阅文档。在阻塞模式下接收的唯一保证是至少传输一个字节,除非流结束或发生错误。