socket recv() 只接收到 1 个字节的数据

Socket recv() receives only 1 byte of data

我试图使用 send() 函数将 "-1" 作为指示器从服务器发送到客户端,但是客户端的 recv() 函数只接收到 1 个字节的数据(recv() 的 return 为 1)。

代码

服务器端:

get_fd(buf, fd, stat_buf)根据buf中的数字获取文件描述符,如果buf中的数字无效[=20]则returns -1 =] 如果一切正常。

if(get_fd(buf, fd, stat_buf) == -1){    // invalid file number
    printf("client has given an invalid file number\n\n");
    if(send(new_sockfd, "-1", 3, 0) == -1){
        perror("client: send");
    }

    close(new_sockfd);
    exit(1);

} else {    // valid file number
    /* code */
}

当我在客户端输入了一个无效的文件号时,第二行的printf()工作正常,没有看到perror()消息。

客户端:

std::memset(&buf, 0, MAXDATASIZE);    // clear the buffer for it has been used previously
if((numbyte = recv(sockfd, buf, MAXDATASIZE-1, 0))==-1){
    perror("client: recv");
    exit(1);
}

buf[numbyte] = '[=11=]';
printf("numbyte: %d, received: %s\n\n", numbyte, buf);

numbyte 始终为 1,而 printf() 对于 buf 不作为 string 打印任何内容,但是当将 buf 打印为 int (%d) 它打印一个无意义的负数,例如 -333179216.

问题出在连接开始时服务器向客户端发送 (send()) 第一条消息时。您将 len 设置为一个比其实际长度大得多的数字。它在开始时工作正常,因为没有更多的通信,但是当您再次尝试 send() 通过该套接字时,问题就会出现。

代码(完整性很重要):

if(send(new_sockfd, "some words here...", 65535, 0) == -1){
    perror("server: send");
}