閱讀482 返回首頁    go 阿裏雲 go 技術社區[雲棲]


網絡編程_多線程的文件上傳小示例

https://blog.csdn.net/zsw101259/article/details/7768908

1、多線程文件的上傳,數據流向 

1)、客戶端Socket:

      ①out File對象 

       ②out 文件內容

        ③in 服務端反饋信息 


2)、服務端的處理 

       ①每接收一個Socket,創建一個線程去處理這個Socket 

        ②in File對象:判斷文件的類型、選擇不同的傳輸方式、創建File對象關聯文件

        ③in 文件內容:填充File對象關聯文件內容 

       ④填充完File文件,給客戶端反饋

  

   2、代碼:                 

  1)客戶端:字符流       

 

[java] view plaincopy
  1. import java.net.*;  
  2. import java.io.*;  
  3. /** 
  4.  * @author Administrator @zsw 2012-7-18 上午09:21:04 
  5.  *  
  6.  * 需求:從客戶端上傳文本文件到服務端 
  7.  *  
  8.  * 客戶端上傳: 
  9.  * ①定義Socket、文件輸入流、Socket輸出流、Socket輸入流 
  10.  * ②從文件輸入讀取文件, 
  11.  * 添加:首先上傳文件File對象和文件類型int filetype 
  12.  * ③將讀到的數據寫入Socket輸出流中 
  13.  * ④關閉資源 
  14.  */  
  15. public class TextUploadClient2 {  
  16.   
  17.       
  18.     public static void main(String[] args) throws Exception{  
  19.         File file=new File("D:\\1.txt");  
  20.           
  21.           
  22.         //①:定義資源  
  23.         Socket s=new Socket("127.0.0.1",10007);  
  24.         BufferedReader bufr=new BufferedReader(new FileReader(file));  
  25.         //字符流轉換成字節流  
  26.         BufferedWriter bufout=new BufferedWriter(  
  27.                 new OutputStreamWriter(s.getOutputStream()));  
  28. //      PrintWriter out=new PrintWriter(s.getOutputStream(),true);  
  29.         BufferedReader bufin=new BufferedReader(  
  30.                 new InputStreamReader(s.getInputStream()));  
  31.           
  32.         //將文件對象傳到服務器  
  33.         ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());  
  34.         oos.writeObject(file);  
  35.           
  36.       
  37.         //②上傳數據  
  38.         String line=null;  
  39.         while((line=bufr.readLine())!=null){  
  40.                
  41. //          System.out.println(line);  
  42.             bufout.write(line);  
  43.             bufout.newLine();  
  44.             bufout.flush();  
  45.         }  
  46.           
  47.         //③告訴服務器,客戶端已經傳完了。並接收服務端的反饋信息  
  48.          s.shutdownOutput();//關閉客戶端的輸出流,相當於在流中寫-1  
  49.            
  50.          String line2=null;  
  51.          while((line2=bufin.readLine())!=null){  
  52.              if("success".equals(line2)){     
  53.                  System.out.println("上傳文件成功!");  
  54.                  break;  
  55.              }  
  56.          }  
  57.           
  58.         //④關閉資源  
  59.          bufr.close();  
  60.          s.close();  
  61.   
  62.   
  63.     }  
  64.   
  65. }  

                                     

2)客戶端:字符流


[java] view plaincopy
  1. import java.io.*;  
  2. import java.net.*;   
  3. /** 
  4.  * @author Administrator @zsw 2012-7-18 下午06:45:41 
  5.  *客戶端: 
  6.  *①服務端點:Socket、流 
  7.  *②讀取客戶端的圖片數據 
  8.  *③通過Socket輸出流將數據發給服務端 
  9.  *④讀取服務端反饋信息 
  10.  *⑤關閉資源 
  11.  */  
  12. public class UploadPicClient2 {  
  13.     public static void main(String[] args) throws Exception{  
  14.         File file=new File("D:\\1.mp3");  
  15.         //①服務端點:  
  16.         Socket s=new Socket("127.0.0.1",10007);  
  17.         FileInputStream fis=new FileInputStream(file);  
  18.         OutputStream out=s.getOutputStream();  
  19.         InputStream in=s.getInputStream();  
  20.           
  21.         //將文件對象傳到服務器  
  22.         ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());  
  23.         oos.writeObject(file);  
  24.           
  25.         //②讀取圖片  
  26.         byte[]buf=new byte[1024*2];  
  27.         int len=0;  
  28.         while((len=fis.read(buf))!=-1){  
  29.             //③發送數據到服務端  
  30.             out.write(buf, 0, len);   
  31.         }  
  32.         //給服務端發送結束標記  
  33.         s.shutdownOutput();  
  34.           
  35.         //④讀取服務端反饋信息  
  36.         len=0;  
  37.         while((len=in.read(buf))!=-1){  
  38.             String str=new String(buf,0,len);  
  39.             System.out.println("服務端反饋:"+str);  
  40.         }  
  41.           
  42.         //⑤關閉資源  
  43.         fis.close();  
  44.         s.close();  
  45.     }  
  46.   
  47. }  

3)服務端:使用多線程

[java] view plaincopy
  1. import java.io.*;  
  2. import java.net.*;  
  3.   
  4. /** 
  5.  * 總結:多線程文件的上傳,數據流向 
  6.  * 1、客戶端Socket:①out File對象 ②out 文件內容 ③in 服務端反饋信息 
  7.  *            
  8.  * 3、服務端的處理 
  9.  *  ①每接收一個Socket,創建一個線程去處理這個Socket 
  10.  *  ②in File對象:判斷文件的類型、選擇不同的傳輸方式、創建File對象關聯文件 
  11.  *  ③in 文件內容:填充File對象關聯文件內容 
  12.  *  ④填充完File文件,給客戶端反饋 
  13.  *   
  14.  *   
  15.  * @author Administrator @zsw 2012-7-18 下午07:03:47 
  16.  * 此類在UploadPicServer.java上麵做改進,使用了多線程. 
  17.  *  
  18.  *1單線程服務端:有局限,當A客戶連接上來後,<br> 
  19.  *被服務器接收後, 服務端執行具體流程中,這時,B客戶端連接,隻有等待。 
  20.  *因為服務端還沒有處理完A客戶端的請求, 
  21.  *還沒有循環回來執行下次 accept方法,所以暫時獲取不到B客戶端對象 
  22.  *  
  23.  *2解決思路:那麼為了可以讓多個客戶端同時並發的訪問服務器,  
  24.  *服務端最好就是將每一個客戶端封裝到一個單獨的線程中。 
  25.  *  
  26.  *  
  27.  *  
  28.  */  
  29. /* 
  30.  * 如何定義線程呢: 明確每一個客戶端要在服務端執行的代碼,將該代碼放入run方法中 
  31.  */  
  32. //3、線程類  
  33. class UploadThread implements Runnable {  
  34.     // 客戶端、文件、文件類型(簡單點0表示文本、1表示字節流)  
  35.     private Socket s;  
  36.     UploadThread(Socket s) {  
  37.         this.s = s;   
  38.     }  
  39.     public void run() {  
  40.         try {  
  41.             Thread.sleep(5000);  
  42.             new FileUpload().upload(s);  
  43.               
  44.         } catch (InterruptedException e) {  
  45.             // TODO Auto-generated catch block  
  46.             e.printStackTrace();  
  47.         }  
  48.           
  49.   
  50.     }  
  51.   
  52. }  
  53.   
  54. // 1、主程序  
  55. public class UploadPicByThread {  
  56.     public static void main(String[] args) throws Exception {  
  57.         // ①定義服務端點:  
  58.         ServerSocket ss = new ServerSocket(10007);  
  59.         //②為每一個客戶端開啟一個  
  60.         int cNum=0;  
  61.         while (true) {  
  62.             Socket s = ss.accept();  
  63.             cNum++;  
  64.             new Thread(new UploadThread(s)).start();  
  65.             System.out.println("上傳成功文件數:"+cNum);  
  66.         }  
  67.   
  68.     }  
  69. }  


4、服務端:業務類,根據不同的上傳,選擇不同的方式

 

[java] view plaincopy
  1. import java.io.*;  
  2. import java.net.*;  
  3.   
  4. // 2、業務類  
  5. public class FileUpload {  
  6.   
  7.     public void upload(Socket s) {  
  8.         try {  
  9.             ObjectInputStream ois=new ObjectInputStream(s.getInputStream());  
  10.             File file=(File)ois.readObject();  
  11.             //當發現文件存在時,修改文件名:如 1.mp3->(count++)1.mp3  
  12.             String name=file.getName();//原始文件名  
  13.             File dir=new File("D:\\tx\\");  
  14.             file=new File(dir,name);  
  15.             int count=0;  
  16.             while(file.exists()){  
  17.                 count++;  
  18.                 file=new File(dir,"("+count+")"+name);  
  19.             }  
  20.             /*當時文本文件時,調用文本上傳方法 
  21.              * 否則調用字符流上傳方法 
  22.              */  
  23.               
  24.             if(name.endsWith(".txt")){  
  25.                 textUpload(s,file);  
  26.             }else{  
  27.                 picUpload(s,file);  
  28.             }  
  29.               
  30.         }  catch (Exception e) {  
  31.             System.out.println(e);  
  32.             System.out.println("上傳失敗");  
  33.         }  
  34.           
  35.     }  
  36.   
  37.     // ①圖片等多媒體文件上傳(字節流)  
  38.     public void picUpload(Socket s, File file)  throws Exception{  
  39.   
  40.             //打印客戶端  
  41.             String ip=s.getInetAddress().getHostAddress();  
  42.             System.out.println(ip+"....connect 準備上傳"+file.getName());  
  43.               
  44.             FileOutputStream fos = new FileOutputStream(file);  
  45.             InputStream in = s.getInputStream();  
  46.             OutputStream out = s.getOutputStream();  
  47.   
  48.   
  49.             // ②讀取數據  
  50.             int len = 0;  
  51.             byte[] buf = new byte[1024 * 2];  
  52.             while ((len = in.read(buf)) != -1) {  
  53.                 fos.write(buf, 0, len);  
  54.             }  
  55.             // ③給客戶端反饋  
  56.             System.out.println(file.getName()+"服務端接收完成");  
  57.             out.write("success".getBytes());  
  58.             // 給客戶端發送結束標記  
  59.             s.shutdownOutput();  
  60.   
  61.             // ④關閉資源  
  62.             fos.close();  
  63.             s.close();  
  64.           
  65.   
  66.     }  
  67.   
  68.     // ②文本上傳(字符流)  
  69.     public void textUpload(Socket s, File file) throws Exception {  
  70.           
  71.             //打印客戶端連接的  
  72.             String ip=s.getInetAddress().getHostAddress();  
  73.             System.out.println(ip+"....connect 準備上傳"+file.getName());  
  74.               
  75.             BufferedWriter bufw = new BufferedWriter(new FileWriter(file));  
  76.             // Socket 輸出輸入  
  77.             BufferedReader bufin = new BufferedReader(new InputStreamReader(  
  78.                     s.getInputStream()));  
  79.             BufferedWriter bufout = new BufferedWriter(new OutputStreamWriter(  
  80.                     s.getOutputStream()));  
  81.   
  82.             // ②:讀數據、寫到文件、判斷結束、反饋成功  
  83.             String line = null;  
  84.             /* 
  85.              * 服務端收不到line=null的情況,必須在流中添加結束標記 s.shutdownOutput(); 
  86.              * 關閉客戶端的輸出流,相當於在流中寫-1,line就可以=null 
  87.              */  
  88.             // 獲取標記符(即時間值)  
  89.             while ((line = bufin.readLine()) != null) {  
  90.                 bufw.write(line);  
  91.                 bufw.newLine();  
  92.                 bufw.flush();  
  93.   
  94.             }  
  95.             System.out.println(file.getName()+"數據接收成功!");  
  96.             bufout.write("success");  
  97.             bufout.newLine();  
  98.             bufout.flush();  
  99.             s.shutdownOutput();  
  100.   
  101.             // 關閉資源  
  102.             bufw.close();  
  103.             s.close();  
  104.           
  105.     }  
  106. }  


最後更新:2017-04-04 07:04:13

  上一篇:go 優酷盜播引版權方圍攻 視頻大佬陷孤軍奮戰困局
  下一篇:go 雲計算管理三大利器:Nagios、Ganglia和Splunk