Android—基於Socket與上傳圖片到客戶端


      最近項目中需要客戶端和Socket互相傳遞數據時候需要相互傳遞圖片所以做下總結以免以后忘記,也希望給大家帶來幫助。

      先上客戶端的代碼:

      根據圖片名稱上傳照相機中單個照片(此方法為自己封裝)

      參數所代表的是照片的路徑。

 private void upload(String path) { int length = 0; byte[] sendBytes = null; Socket socket = null; DataOutputStream dos = null; FileInputStream fis = null; try { try { socket = new Socket(ip,duankou); dos = new DataOutputStream(socket.getOutputStream()); File file = new File(filename); fis = new FileInputStream(file); sendBytes = new byte[1024]; while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) { dos.write(sendBytes, 0, length); dos.flush(); } } finally { if (dos != null) dos.close(); if (fis != null) fis.close(); if (socket != null) socket.close(); } } catch (Exception e) { e.printStackTrace(); } } 

注:在android Activity調用此方法的時候一定要開一個子線程去調用(網絡訪問在主線程中是android中一個標志性的錯誤!!!!)

     接下來是服務端的代碼,測試使用新建一個java類即可

public class Receiver implements Runnable { public static void main(String[] args) { try { final ServerSocket server = new ServerSocket(3333); Thread th = new Thread(new Runnable() { public void run() { while (true) { try { System.out.println("開始監聽..."); Socket socket = server.accept(); System.out.println("有鏈接"); receiveFile(socket); } catch (Exception e) { } } } }); th.run(); // 啟動線程運行
        } catch (Exception e) { e.printStackTrace(); } } public void run() { } public static void receiveFile(Socket socket) { byte[] inputByte = null; int length = 0; DataInputStream dis = null; FileOutputStream fos = null; try { try { dis = new DataInputStream(socket.getInputStream()); fos = new FileOutputStream(new File("./cc.jpg")); inputByte = new byte[1024]; System.out.println("開始接收數據..."); while ((length = dis.read(inputByte, 0, inputByte.length)) > 0) { System.out.println(length); fos.write(inputByte, 0, length); fos.flush(); } System.out.println("完成接收"); } finally { if (fos != null) fos.close(); if (dis != null) dis.close(); if (socket != null) socket.close(); } } catch (Exception e) { } } }

  最后可以在java項目的根目錄下看有沒有成功了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM