Java 簡單TCP檔案傳輸

來源:互聯網
上載者:User

標籤:指定   相等   output   runnable   input   數字   client   cep   trace   

服務端
package TCP;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.ServerSocket;import java.net.Socket;public class TCP_File_Server {    public static void main(String[] args) throws Exception {        /**         * 建立服務端通訊端         */        ServerSocket ss = new ServerSocket();                /**         * 綁定指定連接埠         */        ss.bind(new InetSocketAddress(12345));        System.out.println("《《《《網盤開始運行》》》》");        /**         * 監聽並接受用戶端socket串連,並返回一個socket         */                /**         * 持續接收用戶端發來的資訊,並交給線程處理         */        while(true) {            Socket socket = ss.accept();            new Thread(new UpLoad(socket)).start();        }    }}class UpLoad implements Runnable{        private Socket socket = null;        public UpLoad(Socket socket) {        this.socket = socket;    }        @Override    public void run() {        OutputStream out = null;        try {            // 建立檔案輸入資料流,接收用戶端的socket中的檔案流            InputStream in = socket.getInputStream();            /**             * 擷取檔案名稱長度             * 檔案格式:檔案名稱長度(數字)\r\檔案名稱\r\n檔案內容\r\n             * 擷取檔案名稱 - 讀到第一個斷行符號換行之前 截取出檔案名稱的長度 接著讀取這個長度的位元組 就是檔案名稱             * 讀取資料 直到遇到第一個斷行符號換行             * 每次從流中讀取一個位元組 轉成字串 拼到line上 只要line還不是\r\n結尾 就重複這個過程             */            String line1 = "";            byte[] by1 = new byte[1];            while(!line1.endsWith("\r\n")) {                in.read(by1);                String str = new String(by1);                line1 += str;            }            /**             * 1.讀到長度,去掉\r\n就是檔案名稱字的長度             * 2.parseInt():作用是將可分析的字串轉化為整數。             * 3.substring():返回一個新字串,它是此字串的一個子字串。             */            int len1 = Integer.parseInt(line1.substring(0, line1.length() - 2));            /**             * 1.讀取檔案名稱             * 2.先建立一個長度和檔案名稱長度相等的位元組數組,用來存放檔案名稱             * 3.read(data):從輸入資料流中讀取一定數量的位元組,並將其儲存在緩衝區數組 data 中             *      data數組有多大,就在in輸入資料流裡面讀取多少內容,並將內容存放在data數組裡面             */            byte[] data = new byte[len1];            in.read(data);            String fileName = new String(data);                        // 擷取檔案內容位元組長度            String line2 = "";            byte[] by2 = new byte[1];            while(!line2.endsWith("\r\n")) {                in.read(by2);                String str = new String(by2);                line2 += str;            }            int len2 = Integer.parseInt(line2.substring(0, line2.length() - 2));                        // 建立輸檔案出流,指定檔案輸出地址            String path = "E:/" + fileName;            out = new FileOutputStream(path);            // 擷取檔案內容位元組            // 流對接            byte[] by3 = new byte[len2];            in.read(by3);            out.write(by3);                        System.out.println("接受到來自"+socket.getInetAddress().getHostAddress()+"上傳的檔案"+path);                    } catch (IOException e) {            e.printStackTrace();        }finally {            // 關閉資源            // 關閉輸出資料流            try {                if(out != null) {                    out.close();                }            } catch (IOException e) {                e.printStackTrace();            }finally {                out = null;            }            // 關閉socket            try {                if(socket != null) {                    socket.close();                }            } catch (IOException e) {                e.printStackTrace();            }finally {                socket = null;            }        }    }}
用戶端
package TCP;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.Socket;import java.util.Scanner;public class TCP_File_Client {    public static void main(String[] args) {        Scanner scan = null;        InputStream in = null;        Socket socket = null;                try {            /**             * 1.掃描控制台接收檔案路徑名             *   建立一個file引用,指向一個新的File對象,並給檔案賦予地址             */            System.out.println("請輸入要傳輸檔案的路徑:");            scan = new Scanner(System.in);            String path = scan.nextLine();            File file = new File(path);                        /**             * 2.判斷檔案是文字檔而不是檔案夾並且路徑存在             *  exists():判斷檔案是否存在             *  isFile():判斷是不是檔案              */            if(file.exists() && file.isFile()) {                                /**                 * 3.建立檔案輸入資料流,傳送檔案                  *   將檔案輸入的內容都放在file裡面                 */                in = new FileInputStream(file);                                /**                 * Socket 這個類實現用戶端通訊端(也稱為“通訊端”)。通訊端是兩台機器間通訊的端點。                 *                 * 4.建立用戶端通訊端                 */                socket = new Socket();                //InetSocketAddress Inets = new InetSocketAddress("127.0.0.1", 12345);                                /**                 * 5.串連TCP伺服器                 *       確定服務端的IP和連接埠號碼                 */                socket.connect(new InetSocketAddress("127.0.0.1", 12345));                                /**                 * 6.擷取到用戶端的輸出資料流                 *   OutputStream     getOutputStream()                 *                         返回此通訊端的輸出資料流。                  */                OutputStream out = socket.getOutputStream();                                /**                 * 7.向伺服器傳送檔案                 *   自己定義了一個協議來解決粘包現象,擷取檔案名稱                 *   7.1.我們先將檔案中的內容讀取出來,放到file裡面                 *   7.2.先讀檔案名稱  file.getName()                 *   7.3.將檔案名稱轉換成位元組  file.getName().getBytes()                 *   7.4.擷取檔案名稱的位元組的長度  file.getName().getBytes().length                 *   7.5.再在檔案名稱長度的後面加上  \r\n 作為標識符                 */                // 向伺服器發送[檔案名稱位元組長度 \r\n]                out.write((file.getName().getBytes().length + "\r\n").getBytes());                // 向伺服器發送[檔案名稱位元組]                out.write(file.getName().getBytes());                // 向伺服器發送[檔案位元組長度\r\n]                out.write((file.length() + "\r\n").getBytes());                // 向伺服器發送[檔案位元組內容]                byte[] data = new byte[1024];                int i = 0;                while((i = in.read(data)) != -1) {                    out.write(data, 0, i);                }                            }else {                System.out.println("檔案不存在或者一個檔案~~");            }        } catch (Exception e) {                        e.printStackTrace();        }finally {            /**             * 關閉Scanner,檔案輸入資料流,通訊端             * 通訊端裝飾了輸出資料流,所以不用關閉輸出資料流             */            if(scan != null) {                scan.close();            }            try {                if(in != null) {                    in.close();                }            } catch (IOException e) {                e.printStackTrace();            }finally {                // 強制將輸入資料流置為空白                in = null;            }            try {                if(socket != null) {                    socket.close();                }            } catch (IOException e) {                e.printStackTrace();            }finally {                // 強制釋放socket                socket = null;            }                    }        System.out.println("檔案傳輸完畢");    }}

 

Java 簡單TCP檔案傳輸

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.