簡體   English   中英

從Java服務器向C客戶端發送文本文件

[英]Sending a text file from Java server to C client

我正在嘗試將文本文件從Java服務器發送到C客戶端。 運行我的代碼后,文本文件成功收到但是當我打開它時,我發現文本文件中插入了一些隨機數據。

這是用於發送文件的服務器代碼。

public void sendFile(Socket socket, String file) throws IOException 
{
    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
    FileInputStream fis = new FileInputStream(file);
    byte[] buffer = new byte[256];

    while (fis.read(buffer) > 0) {
        dos.write(buffer);
    }

    fis.close();
    dos.close();    
}

這是用於接收文件的客戶端代碼。

int recv_file(int sock, char* file_name)
{
     char send_str [MAX_SEND_BUF]; 
     int fp; 
     int sent_bytes, rcvd_bytes, rcvd_file_size;
     int recv_count; 
     unsigned int recv_str[MAX_RECV_BUF];
     size_t send_strlen; 
     send_strlen = strlen(send_str); 
     if ( (fp = open(file_name, O_WRONLY|O_CREAT, 0644)) < 0 )
     {
           perror("error creating file");
           return -1;
     }
     recv_count = 0;
     rcvd_file_size = 0;
     while ( (rcvd_bytes = recv(sock, recv_str, MAX_RECV_BUF/*256*/, 0)) > 0 )
     {
           recv_count++;
           rcvd_file_size += rcvd_bytes;
           if (write(fp, recv_str, rcvd_bytes) < 0 )
           {
                  perror("error writing to file");
                  return -1;
           }
           printf("%dThe data received is %u\n", ++count, recv_str);
     }
     close(fp);
     printf("Client Received: %d bytes in %d recv(s)\n", rcvd_file_size,    recv_count);
     return rcvd_file_size;
}

這是客戶端收到的文本文件。 收到的文本文件

這個亂碼被添加到文本文件中,我該如何解決這個問題?

while (fis.read(buffer) > 0) {
    dos.write(buffer);
}

您的副本循環不正確。 如果不是之前,你正在文件的末尾寫垃圾。 它應該是:

int count;
while ((count = fis.read(buffer)) > 0) {
    dos.write(buffer, 0, count);
}

您不應該使用DataOutputStream因為它在這里沒有任何好處。 只需使用socket中的普通OutputStream

然后,您必須確保只寫入文件中的數據。

而不是

while (fis.read(buffer) > 0) {
    dos.write(buffer);
}

采用

OutputStream os = socket.getOutputStream();
int len;
while ( (len = fis.read(buffer)) > 0) {
    os.write(buffer,0,len);
}

確保只寫入文件中的字節數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM