关于java文件传输的问题

哪位大虾帮看一下这段代码~我在本机上面测试可以传输任意大小的文件,虽然速度上不怎么行,  但是跟别的计算机联机传输的时候就会传一点点就断开了  哪位大虾帮看一下
package com.yong.action;
import java.io.*;
import java.net.*;
import javax.swing.*;
/**
 *
 * @author  gzy-gs
 */
public class sendFrame extends javax.swing.JFrame implements Runnable{
     private String fileName="";
     private String IP="";
     Socket toServer;
     BufferedReader streamFromServer;
     ObjectOutputStream streamToServer;
     Thread thisThread;
    /** Creates new form sendFrame */
     ReceiveServer ffff=new ReceiveServer();
    public sendFrame() {
        initComponents();
    }
   
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {//GEN-BEGIN:initComponents
        jFileChooser1 = new javax.swing.JFileChooser();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jProgressBar1 = new javax.swing.JProgressBar();
        jLabel2 = new javax.swing.JLabel();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("\u4f20\u9001\u6587\u4ef6");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });
        jPanel1.setLayout(null);
        jPanel1.setBackground(new java.awt.Color(204, 204, 255));
        jLabel1.setFont(new java.awt.Font("Dialog", 1, 14));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("\u5bf9\u65b9IP");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(10, 20, 60, 20);
        jTextField1.setColumns(20);
       // jTextField1.setEditable(false);
        jPanel1.add(jTextField1);
        jTextField1.setBounds(70, 20, 100, 20);
        jButton1.setBackground(new java.awt.Color(204, 204, 255));
        jButton1.setFont(new java.awt.Font("Dialog", 1, 14));
        jButton1.setText("\u6253\u5f00");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(50, 190, 77, 29);
        jButton2.setBackground(new java.awt.Color(204, 204, 255));
        jButton2.setFont(new java.awt.Font("Dialog", 1, 14));
        jButton2.setText("\u53d1\u9001");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton2);
        jButton2.setBounds(160, 190, 70, 29);
        jButton3.setBackground(new java.awt.Color(204, 204, 255));
        jButton3.setFont(new java.awt.Font("Dialog", 1, 14));
        jButton3.setText("\u53d6\u6d88");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton3);
        jButton3.setBounds(270, 190, 70, 29);
        jTextField2.setColumns(20);
        jTextField2.setEditable(false);
        jTextField2.setFont(new java.awt.Font("Dialog", 1, 14));
        jTextField2.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextField2.setText("\u7b49\u5f85\u56de\u5e94");
        jPanel1.add(jTextField2);
        jTextField2.setBounds(60, 140, 280, 25);
        jProgressBar1.setBackground(new java.awt.Color(153, 0, 204));
        jProgressBar1.setStringPainted(true);
        jPanel1.add(jProgressBar1);
        jProgressBar1.setBounds(60, 100, 280, 21);
        jLabel2.setFont(new java.awt.Font("Dialog", 1, 14));
        jLabel2.setText("\u5df2\u53d1\u9001");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(60, 70, 60, 20);
        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-401)/2, (screenSize.height-300)/2, 401, 300);
    }//GEN-END:initComponents
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
            if(thisThread==null){
                thisThread=new Thread(this);
                thisThread.start();
            }
// TODO 将在此处增加您的处理代码:
    }//GEN-LAST:event_jButton2ActionPerformed
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        this.dispose();// TODO 将在此处增加您的处理代码:
    }//GEN-LAST:event_jButton3ActionPerformed
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
               if (javax.swing.JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this)) {
                   fileName=jFileChooser1.getSelectedFile().getPath();
               }// TODO 将在此处增加您的处理代码:
    }//GEN-LAST:event_jButton1ActionPerformed
   
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
        System.exit(0);
    }//GEN-LAST:event_exitForm
   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        new sendFrame().show();
    }
   
    // 变量声明 - 不进行修改//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // 变量声明结束//GEN-END:variables
   public void setIP(String m){
        IP=m;
        jTextField1.setText(IP);
    }
    public String getIP(){
        return IP;
    }
    public String getFileName(){
        return fileName;
    }
    public void sendData(String fileName)throws Exception{
           byte [] data=new byte[1024];
           String msg;
           String fn=fileName;
           File file=new File(fn);
           long fileLength=file.length();
           streamToServer.writeObject(""+fileLength);
           JOptionPane.showMessageDialog(this,"你要传送的文件大小为"+fileLength+"字节", "Message", JOptionPane.INFORMATION_MESSAGE);
           int i=(int)(fileLength/1024)+1;
           RandomAccessFile fileInput=new RandomAccessFile(file,"r");
           for(int j=0;j<i;j++){
             fileInput.read(data);
             streamToServer.writeObject("send");
             streamToServer.write(data);
             thisThread.sleep(1);
             jProgressBar1.setValue(j);
            
           } 
           fileInput.close();
         
          
    }
   
    public void run() {
        try{
                  //create socket and input-output socket stream
                  toServer=new Socket(jTextField1.getText(),1066);              
                  streamFromServer= new BufferedReader(new InputStreamReader(toServer.getInputStream()));
                  streamToServer=new ObjectOutputStream(toServer.getOutputStream());
                  jTextField2.setText("连接成功");
                 
                  //send message to server for send
                  streamToServer.writeObject("sendData");
                  streamToServer.writeObject(fileName);
     
                  //read the message from the server
                  String frmServer=streamFromServer.readLine();
                  if(frmServer.equals("accept")){
                      jTextField2.setText("对方已同意接收");
                      sendData(fileName);
                      jTextField2.setText("传送结束");
                      jProgressBar1.setValue(0);
                      this.dispose();
                    }
                  if(frmServer.equals("refuse")){
                       jTextField2.setText("对方拒绝接收");
                    }
             }catch(Exception e){
                     System.out.println("Exception Occured: "+e);
             }
    }
}
 
 
 
package com.yong.action;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.util.StringTokenizer;
public class ReceiveServer implements Runnable{
  ServerSocket server;
  Socket fromClient;
  Thread serverThread;
 
  public ReceiveServer(){
   try{
       server=new ServerSocket(1066);
       serverThread=new Thread(this);
       serverThread.start();
   }catch(Exception e){
       System.out.println("Cannot start the thread:"+e);
   }
  }
  public static void main(String args[]){
      new ReceiveServer();
  }
  public void run(){
    try{
        while(true){
          fromClient=server.accept();
          Connect con=new Connect(fromClient);
        }
       }catch(Exception e){
          System.out.println("Cannot listen to the Client"+e);
       }
  }
 }
 class Connect extends JFrame{
     PrintStream streamToClient;
     ObjectInputStream streamFromClient;
     String message="";
     String fileName="";
     JFileChooser jFileChooser1;
     public Connect(Socket inFromClient){
         jFileChooser1 = new JFileChooser();
         try{
             streamFromClient =new ObjectInputStream(inFromClient.getInputStream());
             streamToClient=new PrintStream(inFromClient.getOutputStream());       
             message=(String)streamFromClient.readObject();
             fileName=(String)streamFromClient.readObject();
             if(message.equals("sendData")){                
                 int decide=javax.swing.JOptionPane.showConfirmDialog(null,"你收到文件"+fileName);
                 if(decide==-1||decide==2||decide==1){
                       streamToClient.println("refuse");
                   }
                 if(decide==0){
                       if (JFileChooser.APPROVE_OPTION == jFileChooser1.showSaveDialog(this)) {
                            fileName = jFileChooser1.getSelectedFile().getPath();
                          }
                       streamToClient.println("accept");
                       receiveData(fileName);
                      
                   }
             }
         } catch(Exception e){
   System.out.println("Cannot get the client stream connect" + e);
         }
         finally{
                try{
                     inFromClient.close();
                 }catch(IOException e){
                    
                 }                   
         }
     }
     public void receiveData(String fileName)throws Exception{
          receiver send=new receiver();
          send.show();
          String fn=fileName;
          boolean eof=false;
          String msg;
          byte [] data=new byte[1024];
          File file=new File(fn);
          long fileLength=Integer.parseInt((String)streamFromClient.readObject());
          JOptionPane.showMessageDialog(this,"你所接收的文件大小为"+fileLength+"字节", "Message", JOptionPane.INFORMATION_MESSAGE);
          int i=(int)(fileLength/1024)+1;
          RandomAccessFile fileOutput=new RandomAccessFile(file,"rw");
           for(int j=0;j<i;j++){            
             msg=(String)streamFromClient.readObject();
             if(msg.equals("send")){
              streamFromClient.read(data);
              send.set(j);
              fileOutput.write(data);
             }
             else break;
          } 
          fileOutput.close();
          send.dispose();
    }
   }
 
 
 
 
package com.yong.action;
 
public class receiver extends javax.swing.JFrame {
    private int count;
    /** Creates new form receiver */
    public receiver() {     
        initComponents();
    }
   
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {//GEN-BEGIN:initComponents
        jProgressBar1 = new javax.swing.JProgressBar();
        jLabel1 = new javax.swing.JLabel();
        getContentPane().setLayout(null);
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(204, 204, 255));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });
        jProgressBar1.setBackground(new java.awt.Color(153, 0, 255));
        jProgressBar1.setStringPainted(true);
        getContentPane().add(jProgressBar1);
        jProgressBar1.setBounds(10, 60, 270, 20);
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("\u5df2\u63a5\u6536");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(100, 20, 80, 18);
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-300)/2, (screenSize.height-150)/2, 300, 150);
    }//GEN-END:initComponents
   
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
        System.exit(0);
    }//GEN-LAST:event_exitForm
   
    public void set(int i){
        count=i;
        jProgressBar1.setValue(count);
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        new receiver().show();
    }
   
    // 变量声明 - 不进行修改//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JProgressBar jProgressBar1;
    // 变量声明结束//GEN-END:variables
   
}
 

本文出自 “寻觅” 博客,谢绝转载!

你可能感兴趣的:(java,职场,文件,传输,休闲)