1

这段代码有什么问题(C - Linux)?

我想从服务器接收一个文件,一旦我有一个字节,我立即发送这个字节。但它不起作用。这一点很重要。

int Recv_File(int server,int client,char *buffer_ricezione,size_t dimensione_file){

    ssize_t nwritten,nread;
    size_t n;
    char c;

    for (n=1; n<dimensione_file; n++) {
        nread = recv(server,&c,1,0);
        if (nread == 1) {
            nwritten = send(client,&c,1,0);
        }else{
            return -1; // chiudo connessione con il client
        }
    }
    return 1;
}

谢谢

4

2 回答 2

0

大概,n应该从0开始

for (n=0; n<dimensione_file; n++) {
    nread = recv(server,&c,1,0);
    if (nread == 1) {
        nwritten = send(client,&c,1,0);
    }else{
        return -1; // chiudo connessione con il client
    }
}
于 2013-06-26T02:39:03.193 回答
0

你可以这样尝试,buffer_ricezione 也将被传输的数据填充。一次读取一个字节并发送一个字节是不好的,而且会浪费很多资源。您的代码不会在接收缓冲区中放置任何假设保存传输数据的内容。

 int Recv_File(int server,int client,char *buffer_ricezione,size_t dimensione_file){
 // This code assumes that buffer_recezione has been allocated at least dimensione_file

     ssize_t nwritten,nread;
     size_t n;
     // char c;
     size_t bLeft=dimensione_file;

     while (bLeft > 0)
     {
         nread = recv(server, buffer_ricezione, bLeft, 0);
         if (nread > 0) {
             if ((nwritten = send(client, buffer_ricezione, nread, 0)) != nread)
             {
                  return -1; // impossible to send to the socket, quit
             }
             bLeft -=nread;
             buffer_ricezione += nread;
         }else{
             return -1; // chiudo connessione con il client
         }
     }
     return 1;
 }
于 2013-06-26T17:26:03.743 回答