java-TCP協議發送和接收資料

來源:互聯網
上載者:User

標籤:read   輸入   擷取   des   while   封裝   void   exce   class   

伺服器:

public class FileServerDemo {

    public static void main(String[] args) throws IOException {
        //建立伺服器對象
        ServerSocket ss = new ServerSocket(8080);
        //監聽
        Socket s = ss.accept();
        //封裝通道內的輸入資料流
        BufferedInputStream bis = new BufferedInputStream(
                s.getInputStream());
        //把資料寫入檔案
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream("C:\\Users\\MA\\Desktop\\IOtest\\copy.jpg"));
        byte[] bys = new byte[1024];
        int len = 0;
        while((len = bis.read(bys))!=-1){
            bos.write(bys,0,len);
        }
        //把通道內的輸出資料流封裝
        BufferedWriter write = new BufferedWriter(new OutputStreamWriter(
                s.getOutputStream()));
        write.write("檔案上傳成功");
        write.newLine();
        write.flush();
        //釋放資源
        bos.close();
        s.close();
        ss.close();
    }
}

用戶端:

public class FileClientDemo {

    public static void main(String[] args) throws IOException {
        //建立用戶端對象
        Socket s = new Socket("172.24.60.182",8080);
        //讀取檔案的資料
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\MA\\Desktop\\電路指導書\\QQ圖片20180627212519.jpg"));
        //把通道內的輸出資料流封裝
        BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
        byte[] bys = new byte[1024];
        int len = 0;
        while((len=bis.read(bys))!=-1){
            bos.write(bys,0,len);
        }
        //給伺服器一個反饋
        s.shutdownOutput();//禁用輸出資料流
        //擷取伺服器的反饋資訊
        BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String data = reader.readLine();
        System.out.println("client:"+data);
        bis.close();
        s.close();
    }
}

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.