標籤:style blog color io os ar java 檔案 sp
直接上源碼:
伺服器:
1 package download; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.File; 6 import java.io.FileInputStream; 7 import java.io.IOException; 8 import java.io.OutputStream; 9 import java.net.ServerSocket;10 import java.net.Socket;11 12 /**13 * 目的:利用socket實現檔案的下載。當有用戶端串連到伺服器時,自動從伺服器上下載檔案,用戶端14 * 按照系統毫秒數對下載的檔案命名。15 * 準備:伺服器上準備要下載的檔案d:/1.mp3。用戶端接受檔案後,將檔案儲存在d盤,檔案採取系統毫秒數命名。 16 */17 public class Server {18 19 private ServerSocket ss;20 private int port = 8080;//伺服器開放的連接埠號碼21 /**利用構造方法,初始化ServerSocket*/22 public Server(){23 try {24 ss = new ServerSocket(port);25 } catch (IOException e) {26 e.printStackTrace();27 }28 }29 /**伺服器啟動,等待用戶端進入。當用戶端進入,就產生socket對象,並將該對象交給線程去執行*/30 public void start(){31 while(true){32 try {33 Socket s = ss.accept();//等待用戶端進入34 Thread thread = new Thread(new Handler(s));//利用構造器傳參數35 thread.run();36 } catch (IOException e) {37 e.printStackTrace();38 }39 }40 }41 private class Handler implements Runnable {42 private Socket s;43 private byte[] buf = new byte[1024];//1K大小的緩衝區44 public Handler(Socket s) {45 this.s = s;46 }47 48 public void run() {49 try {50 File sourceFile = new File("d:/1.mp3");51 FileInputStream fis = new FileInputStream(sourceFile);52 BufferedInputStream bis = new BufferedInputStream(fis);53 OutputStream os = s.getOutputStream();54 BufferedOutputStream bos = new BufferedOutputStream(os);55 int size = -1;56 while((size=bis.read(buf))!=-1){57 bos.write(buf,0,size);58 bos.flush();59 }60 s.close();61 fis.close();62 } catch (Exception e) {63 e.printStackTrace();64 }65 }66 67 }68 public static void main(String[] args) {69 Server s = new Server();70 s.start();71 }72 }
用戶端:
1 package download; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.File; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.io.InputStream; 9 import java.net.Socket;10 import java.net.UnknownHostException;11 /**用戶端程式,負責從用戶端下載檔案*/12 public class Client {13 private Socket s;14 private byte[] buf = new byte[1024];//1K大小的緩衝區15 16 public void start(){17 try {18 s = new Socket("192.168.1.103", 8080);19 String fileName = "d:/"+System.currentTimeMillis()+".mp3";20 File targetFile = new File(fileName);21 targetFile.createNewFile();22 FileOutputStream fos = new FileOutputStream(targetFile);23 BufferedOutputStream bos = new BufferedOutputStream(fos);24 InputStream is = s.getInputStream();25 BufferedInputStream bis = new BufferedInputStream(is);26 int size = -1;27 while((size=bis.read(buf))!=-1){28 bos.write(buf,0,size);29 bos.flush();30 }31 s.close();32 fos.close();33 } catch (UnknownHostException e) {34 e.printStackTrace();35 } catch (IOException e) {36 e.printStackTrace();37 }38 }39 public static void main(String[] args) {40 Client c = new Client();41 c.start();42 }43 }
自己動手寫簡單的web應用伺服器(4)—利用socket實現檔案的下載