android連接socket服務器上傳下載多個文件
1.socket服務端SocketServer.java
public class SocketServer { int port = 8888;// 端口號,必須與客戶端一致 // 選擇進行傳輸的文件(測試) String path = "C:\\Temp"; String filePath = "E:\\img.png"; Socket client; public static void main(String arg[]) { System.out.println("-----准備建立socket鏈接----"); new SocketServer().start(); } void start() { try { ServerSocket serverSocket = new ServerSocket(port); while (true) { // IOException偵聽並接受到此套接字的連接。此方法在進行連接之前一直阻塞。 client = serverSocket.accept(); try { System.out.println("-----建立socket鏈接----"); // 向客戶端發送多個文件(測試) setMoreMessage(path); } catch (Exception e) { e.printStackTrace(); } finally { client.close(); System.out.println("close"); } } } catch (Exception e) { e.printStackTrace(); } } // 向客戶端發送信息 private void setMessage(String filePath, DataOutputStream ps) throws IOException { File fi = new File(filePath); System.out.println("要發送的文件長度:" + (int) fi.length() + "字節"); // 向客戶端發送信息 DataInputStream fis = new DataInputStream(new BufferedInputStream( new FileInputStream(filePath))); // 將文件名及長度傳給客戶端。中文名需要處理 ps.writeUTF(fi.getName()); ps.flush(); ps.writeLong((long) fi.length()); ps.flush(); int bufferSize = 8192; byte[] buf = new byte[bufferSize]; while (true) { int read = 0; if (fis != null) { read = fis.read(buf); } if (read == -1) { break; } ps.write(buf, 0, read); } ps.flush(); fis.close(); System.out.println("文件中傳輸。。。"); } /** * 向客戶端發送多個文件 * @param path * @throws IOException */ private void setMoreMessage(String path) throws IOException { File root = new File(path); if (!root.exists()) { root.mkdir(); return; } String[] colum = root.list(); System.out.println("The file's num is :" + colum.length); // 寫入流 DataOutputStream ps = new DataOutputStream(client.getOutputStream()); // 寫出流 DataInputStream dis = new DataInputStream(new BufferedInputStream( client.getInputStream())); // 寫出文件總個數 ps.writeInt(colum.length); ps.flush(); System.out.println(dis.readBoolean() ? "開始上傳文件" : "開始上傳失敗");// 接收客戶端返回的上傳信息 System.out.println(); for (int i = 0; i < colum.length; i++) { System.out.println("The colum's content is :" + colum[i]); String filePath = path + "\\" + colum[i]; setMessage(filePath, ps);// 上傳文件 System.out.println(dis.readBoolean() ? "成功上傳文件" : "上傳失敗");// 接收客戶端返回的上傳信息 } System.out.println("-----文件傳輸完成------"); } // 接收客戶端發送的信息 private void getMessage(DataInputStream inputStream) { try { // 本地保存路徑,文件名會自動從服務器端繼承而來。 String savePath = "D://android_img/"; File file = new File(savePath); // 創建文件夾 if (!file.exists()) { file.mkdirs(); } int bufferSize = 8192; byte[] buf = new byte[bufferSize]; int passedlen = 0; long len = 0; savePath += inputStream.readUTF(); DataOutputStream fileOut = new DataOutputStream( new BufferedOutputStream(new BufferedOutputStream( new FileOutputStream(savePath)))); len = inputStream.readLong(); System.out.println("文件的長度為:" + len + "\n"); System.out.println("開始接收文件!" + "\n" + getTime()); while (true) { int read = 0; if (inputStream != null) { read = inputStream.read(buf); } passedlen += read; if (read == -1) { break; } // 進度條,如果是大文件,可能會重復打印出一些相同的百分比 System.out.println("文件接收了" + (passedlen * 100 / len) + "%\n"); fileOut.write(buf, 0, read); } // 花費的時間 System.out.println("接收完成,文件存為" + savePath + "\n" + getTime()); fileOut.close(); } catch (Exception e) { System.out.println("接收消息錯誤" + "\n" + e.toString()); return; } } public static String getTime() { long tmp = System.currentTimeMillis();// 花費的時間 SimpleDateFormat formatter = new SimpleDateFormat( "yyyy年-MM月dd日-HH時mm分ss秒"); Date date = new Date(tmp); return formatter.format(date); } }
2.android客戶端下文件ImageDownLoadUtil.java
/** * 發送接收文件 * @ClassName: ClientTest * @Description: TODO * @author jalin * @date 2014-4-16 上午11:37:30 */ public class ImageDownLoadUtil extends Thread implements Runnable { private ClientSocket client = null; private Context context; private String IP = "192.168.1.2";// 本地ip private int PORT = 8888; // 端口號 private boolean resule = false; String filePath = "";// android手機文件路徑 String filename = "";//存放圖片的文件夾名 public int type = 0;//模式 public boolean isContinue = true; public ImageDownLoadUtil(Context context) { this.context = context; this.filePath = Session.DATABASE_PATH; filename=Session.IMAGE_FILENAME; try { if (createConnection()) { // type = 2;//接受文件 // sendMessage();//發送文件、信息 type = 1;//接受文件 this.start(); } } catch (Exception ex) { ex.printStackTrace(); } } /** * 得到socket鏈接通道 * @return */ private boolean createConnection() { client = new ClientSocket(IP, PORT); try { client.CreateConnection(); System.out.print("創建連接成功!"); return true; } catch (Exception e) { System.out.print("創建連接失敗!"); return false; } } @Override public void run() { switch (type) { case 1:// 下載多個圖片文件 resule = false; if (client == null) return; DataInputStream inputStream = null;// 寫入流 DataOutputStream out = null;// 寫出流 try { inputStream = client.getDataInputStream();// 寫入流 out = client.getDataOutputStream();// 寫出流 int fileLenght = inputStream.readInt();//得到文件總數量 out.writeBoolean(true);// 發送上傳開始標誌 out.flush(); // 文件存儲路徑 String savePath = filePath + "/" + filename + "/"; while ((fileLenght--) > 0) { resule=saveFile(inputStream,savePath);// 保存圖片 out.writeBoolean(resule);// 發送上傳結果 out.flush(); } } catch (Exception e) { System.out.print("接收文件出錯!"); return; }finally{ Message msg=new Message(); if (resule) { msg.what=1; }else{ msg.what=-1; } handler.sendMessage(msg); } break; default: break; } } /** * 保存文件 * @param inputStream * @return */ private boolean saveFile(DataInputStream inputStream,String savePath) { boolean resule=false; try { if (!new File(savePath).exists()) { new File(savePath).mkdir(); } int bufferSize = 1024 * 8; byte[] buf = new byte[bufferSize]; int passedlen = 0; long len = 0; //得到文件名稱 String saveFilePate=savePath +inputStream.readUTF(); File image = new File(saveFilePate); if (image.exists()) { image.delete(); } DataOutputStream fileOut = new DataOutputStream( new BufferedOutputStream(new BufferedOutputStream( new FileOutputStream(saveFilePate)))); len = inputStream.readLong(); System.out.println("文件長度:" + len); long tmp = System.currentTimeMillis();// 獲取當前系統時間 System.out.println("開始發送時間:" + "\n" + tmp); int redLen = 0; while (true) { int read = 0; if (inputStream != null && passedlen < len) {//文件接收結束標志 read = inputStream.read(buf); } passedlen += read; if (read == -1 || read == 0) { break; } // System.out.println("當前進度:" + (passedlen * 100 / len) + "%\n"); fileOut.write(buf, 0, read); } tmp = System.currentTimeMillis();// 當前時間 System.out.println("文件保存路徑:" + saveFilePate + "---時間:" + tmp); fileOut.close(); resule = true; } catch (Exception e) { System.out.println("出錯了:" + e.toString()); return resule; }finally{ } return resule; } /* * 發送文件、信息 */ private void sendMessage() { if (client == null) return; try { System.out.print("文件路徑:" + filePath); client.sendMessage(filePath); } catch (Exception e) { System.out.print("發送文件出錯!"); } } Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: // 執行定時器時間到了之后由handler傳遞的任務 Toast.makeText(context, "下載圖片成功", Toast.LENGTH_LONG).show(); break; case -1: // 執行定時器時間到了之后由handler傳遞的任務 Toast.makeText(context, "下載圖片失敗", Toast.LENGTH_LONG).show(); break; } super.handleMessage(msg); } }; }
3.Socket客戶端
/** * Socket客戶端 * * @ClassName: ClientSocket * @Description: TODO * @author jalin * @date 2014-4-16 下午5:10:31 */ public class ClientSocket { private String ip; private int port; private Socket socket = null; private DataOutputStream out = null; private DataInputStream getMessageStream = null; public ClientSocket(String ip, int port) { this.ip = ip; this.port = port; } /** * 創建socket連接 * * @throws Exception * exception */ public void CreateConnection() throws Exception { try { socket = new Socket(ip, port); } catch (Exception e) { e.printStackTrace(); if (socket != null) socket.close(); throw e; } finally { } } /** * 發送圖片 * @param filePath * @throws Exception */ public void sendMessage(String filePath) throws Exception { try { // 獲取本地文件 File file = new File(filePath); getMessageStream = new DataInputStream(new BufferedInputStream( new FileInputStream(filePath))); out = new DataOutputStream(socket.getOutputStream()); out.writeUTF(filePath); // 發送文件屬性 out.writeUTF(file.getName()); out.flush(); out.writeLong((long) file.length()); out.flush(); int bufferSize = 1024 * 8; byte[] buf = new byte[bufferSize]; while (true) { int read = 0; if (getMessageStream != null) { read = getMessageStream.read(buf); } if (read == -1) { break; } out.write(buf, 0, read); } out.flush(); getMessageStream.close(); System.out.println("-----發送完成------"); } catch (Exception e) { System.out.println(e.toString()); } finally { if (out != null) out.close(); } } public DataOutputStream getDataOutputStream() { try { out = new DataOutputStream(socket.getOutputStream()); return out; } catch (IOException e) { e.printStackTrace(); try { if (out != null) { out.close(); } } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return null; } public DataInputStream getDataInputStream() throws Exception { try { getMessageStream = new DataInputStream(new BufferedInputStream( socket.getInputStream())); return getMessageStream; } catch (Exception e) { e.printStackTrace(); if (getMessageStream != null) getMessageStream.close(); throw e; } finally { } } public int getFileLenght() { try { return getDataInputStream().readInt(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return -1; } public void shutDownConnection() { try { if (out != null) out.close(); if (getMessageStream != null) getMessageStream.close(); if (socket != null) socket.close(); } catch (Exception e) { } } }
4.activity按鈕事件 new ImageDownLoadUtil(this);
