標籤:反饋 override 檔案 img client host text stack 讀取檔案
//一萬年太久,只爭朝夕
package uploadImg;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;/*建立Socket服務 * 讀取檔案上傳源 * 擷取輸出資料流。將資料發送到服務端 * 告訴服務端資料發送完畢。服務端停止讀取 * 讀取服務端發回的資料 * * * * * */public class ImgClient { public static void main(String[] args) throws UnknownHostException, IOException { Socket s = new Socket("127.0.0.1", 10009); //建立Socket服務 //載入目標檔案 FileInputStream file = new FileInputStream("c:\\0.jpg"); //擷取Socket輸出資料流 OutputStream outputStream = s.getOutputStream(); byte[] buf = new byte[1024]; int len = 0; //將目標檔案讀入byte數組 while ((len = file.read(buf)) != -1) { outputStream.write(buf, 0, len); } s.shutdownOutput(); BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); String readLine = bufIn.readLine(); System.out.println(readLine); bufIn.close(); file.close(); s.close(); }}
package uploadImg;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.ServerSocket;import java.net.Socket;public class ImgServer { /* * 建立ServerSockte服務 擷取Sockte對象 Socket輸入資料流 建立檔案儲存體 多線程。並發 返回反饋結果到用戶端 結束流 */ public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(10009); while (true) { Socket accept = ss.accept(); new Thread(new UploadImg(accept)).start(); } }}
package uploadImg;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.Socket;import java.io.OutputStream;import java.io.PrintWriter;public class UploadImg implements Runnable { private static final int SIZE = 1024 * 1024 * 2; private Socket s; public UploadImg(Socket s) { this.s = s; } @Override public void run() { int count = 0; String ip = s.getInetAddress().getHostName(); System.out.println(ip + "....." + "connect"); try { InputStream inputStream = s.getInputStream(); File dir = new File("c:\\pic"); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, ip + ".jpg"); while (file.exists()) { file = new File(dir, ip + "(" + (count++) + ").jpg"); } FileOutputStream fos = new FileOutputStream(file); byte[] buf = new byte[1024]; int len = 0; while ((len = inputStream.read(buf)) != -1) { fos.write(buf, 0, len); if (file.length() > SIZE) { System.out.println(ip + "檔案體積太大"); fos.close(); s.close(); System.out.println(ip + "..." + file.delete()); return; } } PrintWriter pw = new PrintWriter(s.getOutputStream()); pw.println("上傳成功"); fos.close(); s.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
圖片上傳用戶端與服務端