Android socket 文件傳輸: 用於app更新,大文件上傳下載

<span style="font-size:24px;">客戶端上傳文件</span>
/**
 * 	
 * @author lijp8
 * @input  intent 待傳輸文件的地址
 *	@function 將文件傳輸到服務器,並返回傳輸狀態
 */
	class MyThread extends Thread{

		private Intent intentThread;
		private Socket socket = null;	
		private ArrayList<AttendencePerson> personArray =new ArrayList<AttendencePerson>(); 
		//選擇要傳輸的文件
		//private String filePath= null;
		File fi= new File(DateBaseActivity.dbFilePath);
		
		
		public MyThread(Intent intent){
			this.intentThread= intent;
		}
		@Override
		public void run(){
            //定義消息  
            Message msg = new Message();  
            msg.what = 0x11;  
            Bundle bundle = new Bundle();  
            bundle.clear();  
            try {  
                //連接服務器 並設置連接超時爲5秒  
                socket = new Socket();  
                socket.connect(new InetSocketAddress(DateBaseActivity.IP, 8888), 5000);  
                //獲取輸出流  ,   向服務器發送信息  
                
                DataOutputStream out=new DataOutputStream(socket.getOutputStream());  //向服務器發送消息
                DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(DateBaseActivity.dbFilePath)));
                out.writeUTF(fi.getName());
				out.flush();
				out.writeLong((long)fi.length());
				out.flush();
				byte[] buf= new byte[(int)fi.length()];
				while(true){
					int read =0;
						if(fis!=null)
						{ 
							read=fis.read(buf);
						}else{
							System.out.println("文件傳輸錯誤");
							break;
						}

					if(read ==-1){
						break;
					}

					out.write(buf, 0, read);
					
				}
				out.flush();
				System.out.println("文件傳輸完成");
                 
				//獲取輸入流  ,   接受服務器的信息  
				DataInputStream in = new DataInputStream(socket.getInputStream()); // 接收來自服務器的消息
				String readMsg = in.readUTF();
				
                bundle.putString("msg", readMsg);  
                msg.setData(bundle);  
                //發送消息 修改UI線程中的組件  
                myHandler.sendMessage(msg);  
                //關閉各種輸入輸出流  
                in.close();  
                out.close();  
                socket.close();  
            } catch (SocketTimeoutException aa) {  
                //連接超時 在UI界面顯示消息  
                bundle.putString("msg", "服務器連接失敗!請檢查網絡是否打開");  
                msg.setData(bundle);  
                //發送消息 修改UI線程中的組件  
                myHandler.sendMessage(msg);  
            } catch (IOException e) {  
                e.printStackTrace();  
                Log.w("ljp", e.getClass().getName() + ": " + e.getMessage());     
              //連接超時 在UI界面顯示消息  
                bundle.putString("msg", e.getClass().getName() + ": " + e.getMessage());  
                msg.setData(bundle);  
                //發送消息 修改UI線程中的組件  
                myHandler.sendMessage(msg);  
            }  
        }   
	}
	}


<span style="font-size:18px;">服務端下載程序</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;"></span><pre name="code" class="java">	class ServerDatabaseThread extends Thread{
		public void run() {
			try {
				
				//當前時間
				Date day=new Date();
				SimpleDateFormat df = new SimpleDateFormat("yyyy_MM_dd_HHmmss");
				
				
				ServerSocket ss=new ServerSocket(8888); ////創建一個ServerSocket對象,並讓這個ServerSocket在8888端口監聽				
						
				int i=1;
				while(true){
					Socket socket=ss.accept(); //調用ServerSocket的accept()方法,接受客戶端所發送的請求,如果客戶端沒有發送數據,那麼該線程就停滯不繼續


				try {
						//ObjectInputStream in=new ObjectInputStream(socket.getInputStream());//接收客戶端信息
						DataInputStream in=new DataInputStream(socket.getInputStream());//接收客戶端信息
						DataOutputStream out=new DataOutputStream(socket.getOutputStream());  //向客戶端發送消息
						String savePath= "f:/test/"+df.format(day);
						long fileLen=0;
						int passedLen =0; // 傳輸進度
						
						savePath += in.readUTF();   //讀取數據庫文件名
						fileLen = in.readLong(); //文件長度
						System.out.println("數據庫文件大小:"+fileLen);
						
						byte[] buf= new byte[(int)fileLen];
						DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath))));
						while(true){
							int read =0;
							if(passedLen>=fileLen)
								break;
							
								if(in!=null)
								{ 
									read=in.read(buf);
								}else{
									System.out.println("文件傳輸錯誤");
									//out.writeUTF("文件傳輸錯誤");
									//out.flush();
									break;
								}
							passedLen+=read;
							if(read ==-1){
								break;
							}
							System.out.println( "文件傳輸進度爲"+(passedLen*100/fileLen)+ "%");
							fileOut.write(buf, 0, read);
							
						}
						System.out.println("文件傳輸完成");
						passedLen=0;
						fileOut.close();
						

						out.writeUTF("數據庫上傳完成");
						out.flush();
						
						
						
				
						
						in.close();   //關閉流
						out.close();//關閉流
						
						socket.close();//關閉打開的socket
						
					} catch (Exception e) {
						System.out.println(e.getMessage());
					}
				}
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
		}
	}



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