1.3.1 - 案例104:TCP通訊 上傳檔案
阿新 • • 發佈:2020-11-24
Java Coding 1.3 - TCP通訊:上傳檔案
multithreading 要求:
客戶端給伺服器傳送圖片檔案,伺服器接收檔案並本地化儲存,檔名隨機生成
客戶端
public class ClientDemo { public static void main(String[] args) throws IOException { Socket socket = new Socket("127.0.0.1",10000); //是本地的流,用來讀取本地檔案的. BufferedInputStream bis = new BufferedInputStream( new FileInputStream("text\\桌布.jpg")); //寫到伺服器 --- 網路中的流 OutputStream os = socket.getOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(os); int b; while((b = bis.read())!=-1){ bos.write(b);//通過網路寫到伺服器中 } bos.flush(); //給伺服器一個結束標記,告訴伺服器檔案已經傳輸完畢 socket.shutdownOutput(); BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream())); String line; while((line = br.readLine()) !=null){ System.out.println(line); } bis.close(); socket.close(); } }
伺服器
public class ServerDemo { public static void main(String[] args) throws IOException { // ServerSocket伺服器物件,埠號1000 ServerSocket ss = new ServerSocket(10000); // 建立執行緒池,最多執行緒10 ExecutorService service = Executors.newFixedThreadPool(10); // 伺服器掛起 while (true) { Socket accept = ss.accept(); ThreadSocket ts = new ThreadSocket(accept); service.submit(ts); } } } class ThreadSocket implements Runnable { private Socket acceptSocket; public ThreadSocket(Socket accept) { this.acceptSocket = accept; } @Override public void run() { BufferedOutputStream bos = null; try { //網路中的流,從客戶端讀取資料的 BufferedInputStream bis = new BufferedInputStream(acceptSocket.getInputStream()); //本地的IO流,把資料寫到本地中,實現永久化儲存 bos = new BufferedOutputStream(new FileOutputStream( "text\\桌布.jpg" + UUID.randomUUID().toString() + ".jpg")); int b; while((b = bis.read()) !=-1){ bos.write(b); } BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(acceptSocket.getOutputStream())); bw.write("上傳成功"); bw.newLine(); bw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if(bos != null){ try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (acceptSocket != null){ try { acceptSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }