使用Java Socket进行文件共享被卡住了

时间:2016-09-10 16:38:03

标签: java swing

我正在制作Java swing应用程序,客户端可以从服务器下载文件或在那里上传文件。这里,首先客户端需要在服务器中创建一个帐户,该帐户将在服务器PC中创建一个文件夹。之后,客户将登录他/她的帐户。如果登录成功,则客户端将看到该文件夹​​中的文件,并可以下载文件或将文件上载到该文件夹​​。现在,当我尝试下载文件时,download()方法卡在某一行(第85行)。现在可以解决什么问题呢?

这是我的代码:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package registration;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import javax.swing.*;
import java.net.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Registration {

    /**
     * @param args the command line arguments
     */
    static String str, name, path = "", h, arr[];
    static boolean flag, flag2 = false, flag_array[],connection = false, response = false, response2 = false;
    static File file, file2, f;
    static Socket client;
    static DataInputStream is;
    static DataOutputStream os;
    static int k;
    static class Handle implements Runnable
    {
        Thread t;
        JButton bn;
        boolean flag;

        public Handle(JButton button,boolean flag)
        {
            t = new Thread(this);
            bn = button;
            this.flag = flag;
            t.start();
        }

        public static void download(int i)
        {
            try {
                    os.writeBytes(arr[i]+"->download\n");
                    int filesize=1022386;
                    int bytesRead;
                    int currentTot = 0;
                    byte [] bytearray  = new byte [filesize];
                    InputStream ist = client.getInputStream();
                    File fi = new File(arr[i]);
                    fi.createNewFile();
                    FileOutputStream fos = new FileOutputStream(fi,false);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    bytesRead = ist.read(bytearray,0,bytearray.length);
                    currentTot = bytesRead;

                    do {
                        bytesRead =
                        ist.read(bytearray, currentTot, (bytearray.length-currentTot));
                        if(bytesRead >= 0) currentTot += bytesRead;
                    } while(bytesRead > -1);

                    System.out.println("Done");
                    bos.write(bytearray, 0 , currentTot);
                    bos.flush();
                    bos.close();
                    System.out.println("Done again");
                } catch (IOException ex) {
                    Logger.getLogger(Registration.class.getName()).log(Level.SEVERE, null, ex);
                }
        }

        @Override
        public void run()
        {
            while(flag)
            {
                bn.addActionListener(new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent e)
                    {
                        System.out.println(k + " "+arr[k]);
                        download(k);
                        System.out.println("Done");
                    }
                });
            }
        }
    }

    public static boolean logIn()
    {
        JFrame frame = new JFrame("Log In");
        frame.setSize(700,500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        JLabel label1 = new JLabel("Username: ");
        frame.add(label1,gbc);
        gbc.gridx = 1;
        gbc.gridy = 0;
        JTextField tf1 = new JTextField(20);
        frame.add(tf1,gbc);
        gbc.gridy++;
        gbc.gridx = 0;
        JLabel label2 = new JLabel("Password: ");
        frame.add(label2,gbc);
        gbc.gridx = 1;
        gbc.gridy = 1;
        JTextField tf2 = new JTextField(20);
        frame.add(tf2,gbc);
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 3;
        JButton button = new JButton("Log in");
        frame.add(button,gbc);
        frame.pack();
        frame.setResizable(true);
        frame.setVisible(true);
        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e)
            {
                try {
                    os.writeBytes(tf1.getText() + "->"+tf2.getText()+"\n");
                    String line = is.readLine();
                    if(line.equals("Accepted") == true)
                        flag2 = true;
                    else
                        JOptionPane.showMessageDialog(frame, "Invalid Username or Password", "Error", JOptionPane.ERROR_MESSAGE);
                    response = true;
                } catch (IOException ex) {
                    Logger.getLogger(Registration.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        while(true)
        {
            if(response == true)
                break;
        }

        return flag2;
    }

    /*public static void download(int i)
    {
        try {
                os.writeBytes(arr[i]+" download\n");
                int filesize=1022386;
                int bytesRead;
                int currentTot = 0;
                byte [] bytearray  = new byte [filesize];
                InputStream ist = client.getInputStream();
                FileOutputStream fos = new FileOutputStream(arr[i]);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                bytesRead = ist.read(bytearray,0,bytearray.length);
                currentTot = bytesRead;

                do {
                    bytesRead =
                    ist.read(bytearray, currentTot, (bytearray.length-currentTot));
                    if(bytesRead >= 0) currentTot += bytesRead;
                } while(bytesRead > -1);

                bos.write(bytearray, 0 , currentTot);
                bos.flush();
                bos.close();
            } catch (IOException ex) {
                Logger.getLogger(Registration.class.getName()).log(Level.SEVERE, null, ex);
            }
    }*/

    public static void pass(String line) throws FileNotFoundException
    {
        JFileChooser fc = new JFileChooser();
        arr = line.split(",");
        JFrame frame = new JFrame("Welcome");
        frame.setSize(700,500);
        JMenuBar menubar = new JMenuBar();
        frame.setJMenuBar(menubar);
        JMenu account = new JMenu("Account");
        menubar.add(account);
        JMenuItem up_file = new JMenuItem("Upload File");
        JMenuItem logout = new JMenuItem("Log out");
        account.add(up_file);
        account.add(logout);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        int c = arr.length;
        flag_array = new boolean[c];
        for(int i = 0;i < c;i++)
            flag_array[i] = true;
        JButton button[] = new JButton[c];
        JLabel label[] = new JLabel[c];
        gbc.gridx = 0;
        gbc.gridy = 0;
        for(int i = 0;i < c;i++)
        {
            label[i] = new JLabel(arr[i]);
            gbc.insets = new Insets(10,0,0,0);
            gbc.ipadx = 20;
            frame.add(label[i],gbc);
            gbc.insets = new Insets(10,0,0,0);
            gbc.gridx++;
            button[i] = new JButton("Download File");
            frame.add(button[i],gbc);
            gbc.gridx = 0;
            gbc.gridy++;
        }
        frame.pack();
        JButton ok;
        JTextField tf = new JTextField(15);
        ok = new JButton("OK");
        frame.setVisible(true);
        frame.setResizable(true);
        up_file.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e)
            {
                int returnVal = fc.showOpenDialog(frame);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    file2 = fc.getSelectedFile();
                    path = file2.getAbsolutePath();
                    JFrame frame = new JFrame("Browse File");
                    frame.setSize(700,500);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(tf);
                    frame.add(ok);
                    frame.pack();
                    tf.setText(path);
                    frame.setResizable(true);
                    frame.setVisible(true);
                }
            }
        });
        ok.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e)
            {
                try {
                    String line = file2.getName();
                    os.writeBytes(line + "->upload\n");
                    System.out.println("Accepted connection : " + client);
            File transferFile = new File (path);
            byte [] bytearray  = new byte [(int)transferFile.length()];
            FileInputStream fin = new FileInputStream(transferFile);
            BufferedInputStream bin = new BufferedInputStream(fin);
            bin.read(bytearray,0,bytearray.length);
            OutputStream ost = client.getOutputStream();
            System.out.println("Sending Files...");
            ost.write(bytearray,0,bytearray.length);
            ost.flush();
                    System.out.println("File transfer complete");
                } catch (IOException ex) {
                    Logger.getLogger(Registration.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        Handle h[] = new Handle[c];
        for(int i = 0;i < c;i++)
        {
            h[i] = new Handle(button[i],flag_array[i]);
            /*k = i;
            button[i].addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    System.out.println(k + " "+arr[k]);
                    download(k);
                    System.out.println("Done");
                }
            });*/
        }
        /*for(int i = 0;i < c;i++)
        {
            if(flag_array[i] == true)
                download(i);
        }*/
        logout.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e)
            {
                try {
                    os.writeBytes("Bye\n");
                    connection = true;
                    response2 = true;
                    for(int i = 0;i < c;i++)
                    {
                        flag_array[i] = false;
                        try {
                            h[i].t.join();
                        } catch (InterruptedException ex) {
                            Logger.getLogger(Registration.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    client.close();
                    frame.dispose();
                } catch (IOException ex) {
                    Logger.getLogger(Registration.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        /*button.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e)
        {
            String string = tf.getText();
            if(path.length() == 0)
            {
                if(string.equals(arr[1]) == true)
                {
                    File folder = new File("G:/Java Programming/Input files/"+arr[0]);
                    File[] listOfFiles = folder.listFiles();
                    for (File fi : listOfFiles) {
                        if (fi.isFile()) {
                            fi.setExecutable(true);
                            fi.setReadable(true);
                            fi.setWritable(true);
                        }
                    }
                }
            }
            else
            {
                Path source = Paths.get(path);
                h = tf3.getText();
                Path dest = Paths.get(h);
                    try {
                    Files.copy(source, dest.resolve(source.getFileName()));
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                if(string.equals(arr[1]) == true)
                {
                    File folder = new File("G:/Java Programming/Input files/"+arr[0]);
                    File[] listOfFiles = folder.listFiles();
                    for (File fi : listOfFiles) {
                        if (fi.isFile()) {
                            fi.setExecutable(true);
                            fi.setReadable(true);
                            fi.setWritable(true);
                        }
                    }
                }
            }
        }
        });
        b2.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e)
        {
            String string = tf.getText();
            if(path.length() == 0)
            {
                if(string.equals(arr[1]) == true)
                { 
                    File folder = new File("G:/Java Programming/Input files/"+arr[0]);
                    File[] listOfFiles = folder.listFiles();
                    for (File fi : listOfFiles) {
                        if (fi.isFile()) {
                            fi.setExecutable(false);
                            fi.setReadable(false);
                            fi.setWritable(false);
                        }
                    }
                }
            }
            else
            {
                Path source = Paths.get(path);
                h = tf3.getText();
                Path dest = Paths.get(h);
                    try {
                    Files.copy(source, dest.resolve(source.getFileName()));
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                if(string.equals(arr[1]) == true)
                {
                    File folder = new File("G:/Java Programming/Input files/"+arr[0]);
                    File[] listOfFiles = folder.listFiles();
                    for (File fi : listOfFiles) {
                        if (fi.isFile()) {
                            fi.setExecutable(false);
                            fi.setReadable(false);
                            fi.setWritable(false);
                        }
                    }
                }
            }
        }
        });*/
        while(true)
        {
            if(response2 == true)
                break;
        }
    }

    public static void main(String[] args) throws IOException {
        client = new Socket("127.0.0.1", 1234);
        os = new DataOutputStream(client.getOutputStream());
        is = new DataInputStream(client.getInputStream());
        file = new File("G:/Java Programming/Input files/28/form.txt");
        if(file.exists())
        {
            if(logIn())
            {
                String line = is.readLine();
                pass(line);
            }
        }
        else
        {
            JFrame frame = new JFrame("Registration Form");
            JPanel p = new JPanel();
            frame.setSize(700,500);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            GridBagConstraints gbc = new GridBagConstraints();
            GridLayout g = new GridLayout(1, 3);
            JLabel label1, label2, label3, label4, label5, label6;
            label1 = new JLabel("Name: ");
            JTextField tf1, tf2, tf3;
            JTextArea ta;
            tf1 = new JTextField(25);
            label2 = new JLabel("Roll: ");
            tf2 = new JTextField(10);
            label3 = new JLabel("Address: ");
            ta = new JTextArea(5,30);
            p.setLayout(new GridBagLayout());
            gbc.gridx = 0;
            gbc.gridy = 0;
            //label1.getPreferredSize();
            p.add(label1, gbc);
            gbc.gridx = 1;
            p.add(tf1, gbc);
            gbc.gridx = 2;
            gbc.insets = new Insets(0,1,0,0);
            p.add(label2, gbc);
            gbc.gridx = 3;
            p.add(tf2, gbc);
            gbc.gridx = 0;
            gbc.gridy = 1;
            gbc.ipady = 30;
            gbc.anchor = GridBagConstraints.BASELINE_LEADING;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            p.add(label3, gbc);
            gbc.gridx = 1;
            gbc.gridy = 1;
            gbc.ipadx = 10;
            gbc.gridwidth = 3;
            gbc.fill = GridBagConstraints.BOTH;
            p.add(ta, gbc);
            label4 = new JLabel("Gender:");
            JCheckBox cb1 = new JCheckBox("Male");
            JCheckBox cb2 = new JCheckBox("Female");
            gbc.gridx = 0;
            gbc.gridy = 2;
            p.add(label4,gbc);
            gbc.gridx++;
            p.add(cb1,gbc);
            gbc.gridx+=3;
            p.add(cb2,gbc);
            label5 = new JLabel("Hobby");
            String s[] = {"Playing games", "Watching movies", "Solving problems"};
            JComboBox<String> cox = new JComboBox<>(s);
            gbc.gridx = 0;
            gbc.gridy++;
            p.add(label5,gbc);
            gbc.gridx++;
            gbc.gridwidth = 3;
            p.add(cox,gbc);
            gbc.gridx = 0;
            gbc.gridy++;
            label6 = new JLabel("Password: ");
            p.add(label6, gbc);
            gbc.gridx++;
            gbc.insets = new Insets(0,14,0,0);
            tf3 = new JTextField(20);
            p.add(tf3, gbc);
            gbc.gridy++;
            JButton button = new JButton("Submit");
            gbc.insets = new Insets(0,180,0,180);
            p.add(button,gbc);
            frame.add(p);
            frame.pack();
            button.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    try {
                        name = tf1.getText();
                        str = tf2.getText();
                        File dir = new File("G:/Java Programming/Input files/"+str);
                        dir.mkdirs();
                        file = new File(dir,"form.txt");
                        FileWriter fout = new FileWriter(file);
                        FileWriter fout2 = new FileWriter("G:/Java Programming/Input files/Passwords.txt");
                        fout.write("Name: "+name+"\n");
                        fout.write("Roll no.: "+str+"\n");
                        fout2.write(str+" ");
                        str = ta.getText();
                        fout.write("Address: "+str+"\n");
                        flag = cb1.isSelected();
                        if(flag == true)
                            fout.write("Gender: Male\n");
                        else
                            fout.write("Address: Female\n");
                        str = (String) cox.getSelectedItem();
                        fout.write("Hobby: "+str+"\n");
                        fout.close();
                        str = tf3.getText();
                        fout2.write(str+" form.txt");
                        file.setExecutable(false);
                        file.setReadable(false);
                        file.setWritable(false);
                        fout2.close();
                    } catch (IOException ex) {
                        Logger.getLogger(Registration.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
            frame.setVisible(true);
            frame.setResizable(true);
        }
        /*int c = flag_array.length;
        for(int i = 0;i < c;i++)
        {
            if(flag_array[i] == true)
                download(i);
        }*/
        if(connection == false)
        {    
            os.writeBytes("Bye\n");
            client.close();
        }
    }

}

这是服务器端代码:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package sdpserver;

import java.net.*;
import java.io.*;
import java.util.Scanner;

public class SDPServer {

    /**
     * @param args the command line arguments
     */
    static ServerSocket server;
    static DataOutputStream os;
    static DataInputStream is;
    static Socket client;
    static String arr[];
    public static void download(String str) throws IOException
    {
        System.out.println("Accepted connection : " + client);
    File transferFile = new File ("G:\\Java Programming\\Input files\\"+arr[2]+"\\"+str);
    byte [] bytearray  = new byte [(int)transferFile.length()];
    FileInputStream fin = new FileInputStream(transferFile);
    BufferedInputStream bin = new BufferedInputStream(fin);
    bin.read(bytearray,0,bytearray.length);
    OutputStream ost = client.getOutputStream();
    System.out.println("Sending Files...");
    ost.write(bytearray,0,bytearray.length);
    ost.flush();
        System.out.println("File transfer complete");
    }

    public static void upload(String str) throws FileNotFoundException, IOException
    {
        int filesize=1022386; 
    int bytesRead;
        int currentTot = 0;
        byte [] bytearray  = new byte [filesize];
    InputStream ist = client.getInputStream();
    FileOutputStream fos = new FileOutputStream("G:\\Java Programming\\Input files\\"+arr[2]+str);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    bytesRead = is.read(bytearray,0,bytearray.length);
    currentTot = bytesRead;

    do {
        bytesRead =
        ist.read(bytearray, currentTot, (bytearray.length-currentTot));
        if(bytesRead >= 0) currentTot += bytesRead;
    } while(bytesRead > -1);

        bos.write(bytearray, 0 , currentTot);
    bos.flush();
    bos.close();
    }

    public static void main(String[] args)throws IOException {
        server = new ServerSocket(1234);
        FileReader fin = new FileReader("G:\\Java Programming\\Input files\\Passwords.txt");
        Scanner b = new Scanner(fin);
        String s,req[], files[], names, down[], up[];
        int c;
        File folder = null;
        boolean flag = false;
        client = server.accept();
        is = new DataInputStream(client.getInputStream());
        os = new DataOutputStream(client.getOutputStream());
        while(true)
        {
            String line = is.readLine();
            if(line.contains("download"))
            {
                down = line.split("->");
                download(down[0]);
            }
            else if(line.contains("upload"))
            {
                up = line.split("->");
                upload(up[0]);
            }
            else
            {
                if(line.equals("Bye"))
                    break;
                req = line.split("->");
                while(b.hasNextLine())
                {
                    s = b.nextLine();
                    arr = s.split("->");
                    if((req[0].equals(arr[0])) && (req[1].equals(arr[1])))
                    {
                        os.writeBytes("Accepted\n");
                        folder = new File("G:/Java Programming/Input files/"+arr[2]);
                        flag = true;
                        break;
                    }
                }
                if(flag == false)
                {
                    os.writeBytes("Invalid Username or Password\n");
                    continue;
                }
                files = folder.list();
                c = files.length;
                names = files[0];
                for(int i = 1;i < c;i++)
                {
                    names = names + "," + files[i];
                }
                os.writeBytes(names+"\n");
            }
        }
        client.close();
    }

}

0 个答案:

没有答案