TCP的網絡編程Socket——舉例——從客戶端發送文件給服務端,服務端保存到本地。並返回“發送成功”給客戶端,客戶端接收並輸出。

public class TCPTest3 {

    /*
        這裏涉及到的異常,應該使用try-catch-finally處理
         */
    @Test
    public void client() throws IOException {
        //1.創建Socket對象,指明服務器端的ip和端口號
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
        //2.獲取一個輸出流,用於輸出數據
        OutputStream os = socket.getOutputStream();
        //3.造讀取文件的輸入流

        //可以是一句話 客戶端發送信息一句話給服務端,服務端將數據顯示在控制檯上
        //        os.write("你好,我是客戶端mm".getBytes());

        FileInputStream fis = new FileInputStream(new File("beauty.jpg"));
        //4.數據的輸出過程
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer)) != -1){
            os.write(buffer,0,len);

        }

        //關閉數據的輸出
        socket.shutdownOutput();

        //5.接收來自於服務器端的數據,並顯示到控制檯上
        InputStream is = socket.getInputStream();

        //不建議這樣讀取,可能會有亂碼
//        byte[] buffer = new byte[1024];
//        int len;
//        while((len = is.read(buffer)) != -1){
//            String str = new String(buffer,0,len);
//            System.out.print(str);
//        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bufferr = new byte[20];
        int len1;
        while((len1 = is.read(buffer)) != -1){
            baos.write(bufferr,0,len1);
        }

        System.out.println(baos.toString());

        //6.
        fis.close();
        os.close();
        socket.close();
        baos.close();
    }

    /*
    這裏涉及到的異常,應該使用try-catch-finally處理
     */
    @Test
    public void server() throws IOException {
        //1.創建服務器端的ServerSocket,指明自己的端口號
        ServerSocket ss = new ServerSocket(9090);
        //2.調用accept()表示接收來自於客戶端的socket
        Socket socket = ss.accept();
        //3.獲取輸入流
        InputStream is = socket.getInputStream();

        //4.讀取並保存輸入流中的數據
        FileOutputStream fos = new FileOutputStream(new File("beauty2.jpg"));
        //5.
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }

        System.out.println("圖片傳輸完成");

        //6.服務器端給予客戶端反饋
        OutputStream os = socket.getOutputStream();
        os.write("你好,照片我已收到,非常美!".getBytes());

        //7.
        fos.close();
        is.close();
        socket.close();
        ss.close();
        os.close();

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章