java使用套接字发送文件

mk_*_*mk_ 5 java sockets network-programming

我正在尝试使用Java将文件从一台计算机发送到另一台计算机.我已经编写了下面的代码,如果发送方和接收方都在同一台计算机上启动它可以正常工作,但如果它们在不同的机器上工作,则接收的文件大小比原始文件大,并且它已损坏.

注意:我正在尝试传输最大10 MB的文件.

我怎样才能解决这个问题?

发件人:

ServerSocket server_socket = new ServerSocket(8989);
File myFile = new File(myPath);

Socket socket = server_socket.accept();
int count;
byte[] buffer = new byte[1024];

OutputStream out = socket.getOutputStream();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(myFile));
while ((count = in.read(buffer)) > 0) {
     out.write(buffer, 0, count);
     out.flush();
}
socket.close();
Run Code Online (Sandbox Code Playgroud)

接收器:

Socket socket = new Socket(address, 8989);
FileOutputStream fos = new FileOutputStream(anotherPath);
BufferedOutputStream out = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int count;
InputStream in = socket.getInputStream();
while((count=in.read(buffer)) >0){
    fos.write(buffer);
}
fos.close();
socket.close();
Run Code Online (Sandbox Code Playgroud)

Tom*_*icz 22

在客户端,你写的最多 count的字节,并将它们发送:

while ((count = in.read(buffer)) > 0) {
  out.write(buffer, 0, count);
Run Code Online (Sandbox Code Playgroud)

在服务器端,您读取 count字节 - 但然后您将整个缓冲区写入文件!

while((count=in.read(buffer)) > 0){
  fos.write(buffer);
Run Code Online (Sandbox Code Playgroud)

只需将其更改为:

fos.write(buffer, 0, count);
Run Code Online (Sandbox Code Playgroud)

你会安全的.BTW你的程序有另一个小错误:read()可以返回0并不意味着InputStream结束.>=改为使用:

count = in.read(buffer)) >= 0
Run Code Online (Sandbox Code Playgroud)

您是否考虑IOUtils.copy(InputStream, OutputStream)过Apache Commons?它会将你的整个while循环减少到:

OutputStream out = socket.getOutputStream();
InputStream in = new FileInputStream(myFile);
IOUtils.copy(in, out);
socket.close();
Run Code Online (Sandbox Code Playgroud)

编写的代码更少,测试的代码更少.缓冲是在内部完成的.