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

标签 java c client-server

我正在尝试将文本文件从 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;
}

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

这个乱码被添加到文本文件中,我该如何解决这个问题?

最佳答案

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

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

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

关于java - 将文本文件从 Java 服务器发送到 C 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46340397/

相关文章:

Linux操作系统下C语言的客户端和服务器通信

java - Spring 的 NumberFormat 线程安全

java - ./* 和 ./* 之间有什么区别? :./* 在 java 类路径中

c - C 中带有指针的缓冲区

c - 有什么方法可以在我的程序中使用常量而不将其存储在内存中?

java - 在小型聊天客户端中通过静态引用成员发送类实例

java - 找不到主类: Program will exit

Java/Mockito : Set up 'when' for list arg containing element

c - 在阻塞时获取 SIGSEGV 信号

Java-Socket : Multiple Clients error