Home Java javaTutorial Detailed introduction of Java Socket to implement breakpoint resume transfer of files (code example)

Detailed introduction of Java Socket to implement breakpoint resume transfer of files (code example)

Mar 13, 2019 am 11:59 AM
java

What this article brings to you is a detailed introduction to the Java Socket implementation file's breakpoint resumption method (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.

Some time ago, because the task required me, a java scumbag, I started to study how to use java to implement a simple file breakpoint resume transfer. My understanding of the so-called file resuming is that when the file is transferred due to some reasons, the program stops running and the file is terminated. When the file is re-transmitted next time, the file can be transferred from the location of the last transfer without having to re-transmit it. Start from scratch.

The file transfer process is divided into the sender and the receiver. In the end, my idea is this:

1: Before the transfer starts, the sender first sends a confirmation message to the receiver, and then Send the file name of the file to be sent to the receiver
2: After the receiver receives the confirmation message, it receives the file name sent from the sender. After receiving it, it sends a confirmation message to the sender to indicate that the file name has been received. The receiver then creates a ".temp" File object and a ".temp" RandomAccessFile object based on the received file name. Get the length (size) of the file corresponding to this File object (this length is the length that the receiver has accepted. If the file has not been received before, the length is 0), and sends the file length to the sender.
3: After the sender receives the confirmation message, it receives the file length sent by the recipient, then sends the total length of the file to be sent to the recipient, and sends a confirmation message to the recipient. Then according to the length of the file sent by the recipient, the sending starts from the position corresponding to the length of the file.
4: After receiving the confirmation message, the receiver accepts the data sent by the sender, and then writes it from the end of the file. After acceptance is complete, rename the ".temp" file to a normal file name.

Drawing the process as a diagram is as follows:

Detailed introduction of Java Socket to implement breakpoint resume transfer of files (code example)

can realize the interruption The key to resuming the upload is to use RandomAccessFile. This type of instance supports reading and writing of random access files.

Add some GUIs such as progress bars and file selectors, and the final main code As follows:

Sender code:

import
 java.awt.Color;
import
 java.awt.Container;
import
 java.awt.Dimension;
import
 java.awt.FlowLayout;
import
 java.awt.event.ActionEvent;
import
 java.awt.event.ActionListener;
import
 java.io.DataInputStream;
import
 java.io.DataOutputStream;
import
 java.io.File;
import
 java.io.IOException;
import
 java.io.RandomAccessFile;
import
 java.net.Socket;
import
 javax.swing.BoxLayout;
import
 javax.swing.JButton;
import
 javax.swing.JFileChooser;
import
 javax.swing.JFrame;
import
 javax.swing.JLabel;
import
 javax.swing.JOptionPane;
import
 javax.swing.JPanel;
import
 javax.swing.JProgressBar;
public class
 SendFile 
extends
 Thread{
  
private
 Socket socket=null;
  
private
 DataOutputStream dos;
  
private
 DataInputStream dis;
  
private
 RandomAccessFile rad;
  
private
 Container contentPanel;
      
private
 JFrame frame;
      
private
 JProgressBar progressbar;
      
private
 JLabel label;
  
public
 SendFile(){
    frame=
new
 JFrame("
文件传输
");
    
try
 {
          socket=new Socket("localhost", 8080);
     } 
catch
 (IOException e) {
     
 // TODO Auto-generated catch block
     e.printStackTrace();
      }
   }
  public void
 run(){
    JFileChooser fc = 
new
 JFileChooser();
   int status=fc.showOpenDialog(
null
);
    
if
 (status==JFileChooser.
APPROVE_OPTION
) {
    String 
path
=fc.getSelectedFile().getPath();
    try {
      dos=
new
 DataOutputStream(socket.getOutputStream());
      dis=
new
 DataInputStream(socket.getInputStream());
      dos.writeUTF("
ok
");
      rad=
new
 RandomAccessFile(path, "
r
");
      File file=
new
 File(path);
      byte[] buf=
new
 byte[1024];
      dos.writeUTF(file.getName());
      dos.flush();
      String rsp=dis.
readUTF
();
      
if
 (rsp.equals("ok")) {
          long size=dis.readLong();
//读取文件已发送的大小
         dos.writeLong(rad.length());
          dos.writeUTF("
ok
");
         dos.flush();
          long offset=size;
//字节偏移量
          int barSize=(int) (rad.length()/1024);
          int barOffset=(int)(offset/1024);
         
 //传输界面
         frame.setSize(380,120);
          contentPanel = frame.getContentPane();
          contentPanel.setLayout(
new
 BoxLayout(contentPanel, BoxLayout.
Y_AXIS
));
          progressbar = new JProgressBar();
//进度条
           label=new JLabel(file.getName()+" 
发送中
");
          contentPanel.add(label);
          progressbar.setOrientation(JProgressBar.
HORIZONTAL
);
          progressbar.setMinimum(0);
          progressbar.setMaximum(barSize);
          progressbar.setValue(barOffset);
              progressbar.setStringPainted(true);
              progressbar.setPreferredSize(
new
 Dimension(150, 20));
              progressbar.setBorderPainted(true);
              progressbar.setBackground(
Color
.pink);
              JButton cancel=
new
 JButton("
取消
");
              JPanel barPanel=
new
 JPanel();
              barPanel.setLayout(
new
 FlowLayout(FlowLayout.
LEFT
));
              barPanel.add(progressbar);
              barPanel.add(cancel);
              contentPanel.add(barPanel);    
              cancel.addActionListener(
new
 CancelActionListener());
          frame.setDefaultCloseOperation(
          JFrame.
EXIT_ON_CLOSE
);
          frame.setVisible(
true
);
         
 //从文件指定位置开始传输
          int length;
          
if
 (offset<rad.length()) {
             rad.seek(offset);
            
while
((length=rad.read(buf))>0){
               dos.write(buf,0,length);
              progressbar.setValue(++barOffset);
              dos.flush();
          }
         }
          label.setText(file.getName()+" 
发送完成
");
           }
      dis.close();
      dos.close();
      rad.close();
    } 
catch
 (IOException e) {
        
  // TODO Auto-generated catch block
      label.setText("
 取消发送,连接关闭
");
    }
finally
 {
      frame.dispose();
    }
  }
}
class
 CancelActionListener 
implements
 ActionListener{
  
public void
 actionPerformed(ActionEvent e3){
    
try
 {
      label.setText(" 
取消发送,连接关闭
");
      JOptionPane.showMessageDialog(frame, "
取消发送给,连接关闭!
", "
提示:
", JOptionPane.
INFORMATION_MESSAGE
);
      dis.close();
      dos.close();
      rad.close();
      frame.dispose();
      socket.close();
    } 
catch
 (IOException e1) {
   }
   }
 }
}

Receiver code:

import
 java.awt.Color;
import
 java.awt.Container;
import
 java.awt.Dimension;
import
 java.awt.FlowLayout;
import
 java.awt.event.ActionEvent;
import
 java.awt.event.ActionListener;
import
 java.io.DataInputStream;
import
 java.io.DataOutputStream;
import
 java.io.File;
import
 java.io.IOException;
import
 java.io.RandomAccessFile;
import
 java.net.ServerSocket;
import
 java.net.Socket;
import
 javax.swing.BoxLayout;
import
 javax.swing.JButton;
import
 javax.swing.JFrame;
import
 javax.swing.JLabel;
import
 javax.swing.JOptionPane;
import
 javax.swing.JPanel;
import
 javax.swing.JProgressBar;
public class
 ReceiveFile 
extends
 Thread{
  
private
 ServerSocket connectSocket=null;
  
private
 Socket socket=null;
  
private
 JFrame frame;
  
private
 Container contentPanel;
  
private
 JProgressBar progressbar;
  
private
 DataInputStream dis;
  
private
 DataOutputStream dos;
  
private
 RandomAccessFile rad;
  
private
 JLabel label;
   
public
 ReceiveFile(){
     frame=
new
 JFrame("
接收文件
");
    
try
 {
      connectSocket=
new
 ServerSocket(8080);
      socket=connectSocket.accept();
   } 
catch
 (IOException e) {
      
// TODO Auto-generated catch block
      e.printStackTrace();
   }
  }
   public void
 run(){
   try
 {
    dis=
new
 DataInputStream(socket.getInputStream());
    dos=
new
 DataOutputStream(socket.getOutputStream());
    dis.readUTF();
    int permit=JOptionPane.showConfirmDialog(frame, "
是否接收文件","文件传输请求:
", JOptionPane.
YES_NO_OPTION
);
    
if
 (permit==JOptionPane.
YES_OPTION
) {
      String filename=dis.
readUTF
();
      dos.writeUTF("
ok
");
      dos.flush();
      File file=
new
 File(filename+"
.temp
");
      rad=
new
 RandomAccessFile(filename+"
.temp
", "
rw
");
      
//获得文件大小
      long size=0;
      
if
(file.exists()
&&
 file.isFile()){
        size=file.length();
      }
      dos.writeLong(size);
//发送已接收的大小
      dos.flush();
      long allSize=dis.readLong();
      String rsp=dis.
readUTF
();
      
int
 barSize=(
int
)(allSize/1024);
      int barOffset=(
int
)(size/1024);
      
//传输界面
      frame.setSize(300,120);
      contentPanel =frame.getContentPane();
      contentPanel.setLayout(new 
BoxLayout
(contentPanel, BoxLayout.
Y_AXIS
));
      progressbar = 
new
 JProgressBar();
//进度条
      label=
new
 JLabel(filename+" 
接收中
");
      contentPanel.add(label);
      progressbar.setOrientation(JProgressBar.
HORIZONTAL
);
      progressbar.setMinimum(0);
      progressbar.setMaximum(barSize);
      progressbar.setValue(barOffset);
          progressbar.setStringPainted(true);
          progressbar.setPreferredSize(
new
 Dimension(150, 20));
          progressbar.setBorderPainted(
true
);
          progressbar.setBackground(
Color
.pink);
          JButton cancel=
new
 JButton("
取消
");
          JPanel barPanel=
new
 JPanel();
          barPanel.setLayout(new 
FlowLayout
(FlowLayout.
LEFT
));
          barPanel.add(progressbar);
          barPanel.add(cancel);
          contentPanel.add(barPanel);
          cancel.addActionListener(
new
 CancelActionListener());
          frame.setDefaultCloseOperation(
          JFrame.
EXIT_ON_CLOSE
);
          frame.setVisible(
true
);
          
//接收文件
      
if
 (rsp.equals("
ok
")) {
        rad.seek(size);
        int length;
        byte[] buf=
new
 byte[1024];
        while((length=dis.read(buf, 0, buf.length))!=-1){
          rad.write(buf,0,length);
          progressbar.setValue(++barOffset);
        }
        System.
out
.println("
FileReceive end...
");
      }
      label.setText(filename+" 
结束接收
");
      dis.close();
      dos.close();
      rad.close();
      frame.dispose();
      
//文件重命名
      
if
 (barOffset>=barSize) {
        file.renameTo(new File(filename));
       }
    }
else
{
      dis.close();
      dos.close();
      frame.dispose();
    }
    } 
catch
 (IOException e) {
      
// TODO Auto-generated catch block
      label.setText("
 已取消接收,连接关闭!
");
    }
finally
 {
      frame.dispose();
    }
  }
class
 CancelActionListener 
implements
 ActionListener{
  
public void
 actionPerformed(ActionEvent e){
    
try
 {
      dis.close();
      dos.close();
      rad.close();
      JOptionPane.showMessageDialog(frame, "
已取消接收,连接关闭!
", "
提示:
", JOptionPane.
INFORMATION_MESSAGE
);
      label.setText(" 
取消接收,连接关闭
");
    } 
catch
 (IOException e1) {
    }
   }
  }
}

Receiver test:

public class
 FileReceiveTest{
//接收方
  
public static void
 main(String[] args) {
    // TODO Auto-generated method stub 
    ReceiveFile rf=
new
 ReceiveFile();
    rf.start();
  }
}

Sender test:

public class FileSendTest{
//发送方
  
public static void
 main(String[] args) {
    
// TODO Auto-generated method stub
    SendFile sf=new SendFile();
    sf.start();
  }
}

Pay attention to running the receiver code first and then the sender code. When testing, we choose a larger file. I chose a movie file here. The running results are as follows:

First, there will be a prompt whether to receive or not. Box

After clicking Yes, it will start receiving, and clicking No will cancel it

It has ended successfully!

The above is the detailed content of Detailed introduction of Java Socket to implement breakpoint resume transfer of files (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is a deadlock in Java and how can you prevent it? What is a deadlock in Java and how can you prevent it? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

How to use Optional in Java? How to use Optional in Java? Aug 22, 2025 am 10:27 AM

UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor

Java Persistence with Spring Data JPA and Hibernate Java Persistence with Spring Data JPA and Hibernate Aug 22, 2025 am 07:52 AM

The core of SpringDataJPA and Hibernate working together is: 1. JPA is the specification and Hibernate is the implementation, SpringDataJPA encapsulation simplifies DAO development; 2. Entity classes map database structures through @Entity, @Id, @Column, etc.; 3. Repository interface inherits JpaRepository to automatically implement CRUD and named query methods; 4. Complex queries use @Query annotation to support JPQL or native SQL; 5. In SpringBoot, integration is completed by adding starter dependencies and configuring data sources and JPA attributes; 6. Transactions are made by @Transactiona

Java Cryptography Architecture (JCA) for Secure Coding Java Cryptography Architecture (JCA) for Secure Coding Aug 23, 2025 pm 01:20 PM

Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time

LOL Game Settings Not Saving After Closing [FIXED] LOL Game Settings Not Saving After Closing [FIXED] Aug 24, 2025 am 03:17 AM

IfLeagueofLegendssettingsaren’tsaving,trythesesteps:1.Runthegameasadministrator.2.GrantfullfolderpermissionstotheLeagueofLegendsdirectory.3.Editandensuregame.cfgisn’tread-only.4.Disablecloudsyncforthegamefolder.5.RepairthegameviatheRiotClient.

How to use the Pattern and Matcher classes in Java? How to use the Pattern and Matcher classes in Java? Aug 22, 2025 am 09:57 AM

The Pattern class is used to compile regular expressions, and the Matcher class is used to perform matching operations on strings. The combination of the two can realize text search, matching and replacement; first create a pattern object through Pattern.compile(), and then call its matcher() method to generate a Matcher instance. Then use matches() to judge the full string matching, find() to find subsequences, replaceAll() or replaceFirst() for replacement. If the regular contains a capture group, the nth group content can be obtained through group(n). In actual applications, you should avoid repeated compilation patterns, pay attention to special character escapes, and use the matching pattern flag as needed, and ultimately achieve efficient

Edit bookmarks in chrome Edit bookmarks in chrome Aug 27, 2025 am 12:03 AM

Chrome bookmark editing is simple and practical. Users can enter the bookmark manager through the shortcut keys Ctrl Shift O (Windows) or Cmd Shift O (Mac), or enter through the browser menu; 1. When editing a single bookmark, right-click to select "Edit", modify the title or URL and click "Finish" to save; 2. When organizing bookmarks in batches, you can hold Ctrl (or Cmd) to multiple-choice bookmarks in the bookmark manager, right-click to select "Move to" or "Copy to" the target folder; 3. When exporting and importing bookmarks, click the "Solve" button to select "Export Bookmark" to save as HTML file, and then restore it through the "Import Bookmark" function if necessary.

'Java is not recognized' Error in CMD [3 Simple Steps] 'Java is not recognized' Error in CMD [3 Simple Steps] Aug 23, 2025 am 01:50 AM

IfJavaisnotrecognizedinCMD,ensureJavaisinstalled,settheJAVA_HOMEvariabletotheJDKpath,andaddtheJDK'sbinfoldertothesystemPATH.RestartCMDandrunjava-versiontoconfirm.

See all articles