1. 程式人生 > >Java基於TCP協議的Socket客戶端檔案上傳與下載

Java基於TCP協議的Socket客戶端檔案上傳與下載

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;
 
public class FileUp{
    // 上傳的檔案路徑
    private String filePath;
    // socket伺服器地址和埠號
    private String host;
    private int port;
 
    public String getFilePath() {
        return filePath;
    }
 
    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
 
    public int getPort() {
        return port;
    }
 
    public void setPort(int port) {
        this.port = port;
    }
 
    public String getHost() {
        return host;
    }
 
    public void setHost(String host) {
        this.host = host;
    }
    
    public static void main(String[] args) {
        FileUp fu = new FileUp();
        fu.setHost("127.0.0.1");
        fu.setPort(9005);
        fu.setFilePath("f:\\soft\\");
        fu.uploadFile("DbVisualizer.rar");
    }
 
    /**
     * 客戶端檔案上傳
     * @param fileName 檔名
     */
    public void uploadFile(String fileName) {
        Socket s = null;
        try {
            s = new Socket(host, port);
 
            // 選擇進行傳輸的檔案
            File fi = new File(filePath + fileName);
            System.out.println("檔案長度:" + (int) fi.length());
 
            DataInputStream fis = new DataInputStream(new FileInputStream(filePath + fileName));
            DataOutputStream ps = new DataOutputStream(s.getOutputStream());
            ps.writeUTF(fi.getName());
            ps.flush();
            ps.writeLong((long) fi.length());
            ps.flush();
 
            int bufferSize = 8192;
            byte[] buf = new byte[bufferSize];
 
            while (true) {
                int read = 0;
                if (fis != null) {
                    read = fis.read(buf);
                }
 
                if (read == -1) {
                    break;
                }
                ps.write(buf, 0, read);
            }
            ps.flush();
            // 注意關閉socket連結哦,不然客戶端會等待server的資料過來,
            // 直到socket超時,導致資料不完整。
            fis.close();
            ps.close();
            s.close();
            System.out.println("檔案傳輸完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
 
 
 
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
 
public class FileDown extends Thread {
    // 檔案的儲存路徑
    private String fileDir;
    // socket伺服器埠號
    private int port;
    // 是否停止
    private boolean stop;
 
    public String getFileDir() {
        return fileDir;
    }
 
    public void setFileDir(String fileDir) {
        this.fileDir = fileDir;
    }
 
    public int getPort() {
        return port;
    }
 
    public void setPort(int port) {
        this.port = port;
    }
 
    public boolean isStop() {
        return stop;
    }
 
    public void setStop(boolean stop) {
        this.stop = stop;
    }
    
    public static void main(String[] args) {
        FileDown fd = new FileDown();
        fd.setFileDir("e:\\");
        fd.setPort(9005);
        fd.start();
    }
 
    /**
     * 檔案下載
     */
    @Override
    public void run() {
        Socket socket = null;
        try {
            ServerSocket ss = new ServerSocket(port);
            do {
                socket = ss.accept();
 
                // public Socket accept() throws
                // IOException偵聽並接受到此套接字的連線。此方法在進行連線之前一直阻塞。
                System.out.println("建立socket連結");
                DataInputStream inputStream = new DataInputStream(
                        new BufferedInputStream(socket.getInputStream()));
                
                // 本地儲存路徑,檔名會自動從伺服器端繼承而來。
                int bufferSize = 8192;
                byte[] buf = new byte[bufferSize];
                long passedlen = 0;
                long len = 0;
 
                // 獲取檔名
                String file=fileDir + inputStream.readUTF();
                DataOutputStream fileOut = new DataOutputStream(
                        new BufferedOutputStream(new FileOutputStream(file)));
                len = inputStream.readLong();
 
                System.out.println("檔案的長度為:" + len + "\n");
                System.out.println("開始接收檔案!" + "\n");
 
                while (true) {
                    int read = 0;
                    if (inputStream != null) {
                        read = inputStream.read(buf);
                    }
                    passedlen += read;
                    if (read == -1) {
                        break;
                    }
                    // 下面進度條本為圖形介面的prograssBar做的,這裡如果是打檔案,可能會重複打印出一些相同的百分比
                    System.out.println("檔案接收了" + (passedlen * 100 / len)
                            + "%\n");
                    fileOut.write(buf, 0, read);
                }
                System.out.println("接收完成,檔案存為" + file + "\n");
 
                fileOut.close();
            } while (!stop);
        } catch (Exception e) {
            System.out.println("接收訊息錯誤" + "\n");
            e.printStackTrace();
            return;
        }
    }
}