无法在FTP中实现SwingWorker

时间:2017-07-09 06:28:48

标签: java tcp ftp swingworker

我正在尝试使用Java中的TCP / IP创建FTP。在IDE中一切正常,但后来我决定通过引入GUI使其成为独立于IDE的应用程序。为了更新GUI我实现了SwingWorker。这是我的Client.java的代码,问题出现了。传输成功但Stream没有刷新,并且由于文件被破坏而没有关闭连接。此外,GUI不会更新。

接收方法

 public void receive()throws Exception
{
    String ipadd = ipaddress.getText();
    String port1 = socketname.getText();
    String filepath = directory.getText();
    String filepath1 = filepath.replaceAll("\\\\", "/");
    String filename1 = name.getText();
    String finalpath = filepath1+"/"+filename1;

    int port = Integer.parseInt(port1);
    Socket s = new Socket(ipadd,port);
        byte[] contents = new byte[10000];


        File file = new File(finalpath);

        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        DataInputStream is = new DataInputStream(s.getInputStream());

        long fileLength = is.readLong();
             while((bytesRead = is.read(contents))!=1) {
        SwingWorker<Void,Integer> worker = new SwingWorker<Void,Integer>() {
                @Override
                protected Void doInBackground() throws Exception {
                    totalbytesread+= bytesRead;
                    bos.write(contents, 0 ,bytesRead);
                    publish(totalbytesread);
                    return null;
                }
                @Override
                protected void process(List<Integer> chunks) {
                    int value = chunks.get(chunks.size() - 1);
                    System.out.println(value);
                    progress.setText("Received "+(value/1000000)+" MB out 

                   of "+(fileLength/1000000)+" MB.......("+

                   (value*100)/fileLength+"%)");
                    super.process(chunks); 
                } 
                @Override
                protected void done() {
                    progress.setText("File Received!!");
                    super.done(); 
            }

            };worker.execute();   
             }                
            bos.flush();
            s.close();

    Toolkit.getDefaultToolkit().beep();
    JOptionPane.showMessageDialog(null, "File Successfully Received!!");
}

请帮助..

0 个答案:

没有答案