将文本文件从 Java 服务器发送到 C 客户端

Sending a text file from Java server to C client

我正在尝试将文本文件从 Java 服务器发送到 C 客户端。在我 运行 我的代码之后,文本文件被成功接收,但是当我打开它时,我发现一些 运行dom 数据已经被插入到文本文件中。

这是发送文件的服务器代码。

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;
}

这是客户端收到的文本文件。 Received text file

此乱码已添加到文本文件中,我该如何解决此问题?

您不应使用 DataOutputStream,因为它在这里没有任何好处。只需使用套接字中的普通 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);
}

确保只写入文件中的字节数。

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

您的复制循环不正确。你在文件末尾写垃圾,如果不是之前的话。应该是:

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