天天看點

socket網絡程式設計之檔案的上傳下載下傳

  • socket套接字

用于描述ip位址和端口号,是一個通訊鍊的句柄(java的應用)在internet上的一個主句,一般運作多個伺服器的軟體,

同時就提供多個服務,每個服務監聽一個端口,不同的端口對應的不同的服務

最終應用程式和伺服器通過socket套接字建立網絡連接配接,發送和接收請求

  • 服務端套接字:
    socket網絡程式設計之檔案的上傳下載下傳
  • 用戶端套接字:
socket網絡程式設計之檔案的上傳下載下傳

就不多說了,直接看代碼吧,寫的一個簡單的檔案上傳和下載下傳功能,可能不是很成熟,希望能對你有幫助

/**
 * 服務端
 * @author PC
 */
public class Server {
	public static void main(String[] args) throws Exception {
		// 建立ServerSocket對象
		ServerSocket ss = new ServerSocket(9991);
		System.out.println("伺服器已經啟動...");
		while (true) {
			// 開始監聽9991端口
			Socket s = ss.accept();
			// 僅代表run邏輯
			ThreadHandler th = new ThreadHandler(s);
			Thread t = new Thread(th);
			t.start();

		}
	}
}
           
/**
 * 服務端線程
 * @author PC
 */
public class ThreadHandler implements Runnable {
	private Socket socket;
	public ThreadHandler(Socket socket) {
		this.socket = socket;
	}
	@Override
	public void run() {
		try {
			// 下載下傳檔案
			// 擷取用戶端ip位址
			InetAddress ip = socket.getInetAddress();
			// 建構網絡輸入流
			DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
			// 建構網絡輸出流
			DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
			// 接收傳過來的操作
			String cz = dis.readUTF();
			if (cz != null && "1".equals(cz)) {
				ServerDownload sd = new ServerDownload();
				sd.getServerDownload(dis, dos);
			} else if (cz != null && "2".equals(cz)) {
				SeverUpload su = new SeverUpload();
				su.getServerUpload(dis, dos);
			} else {
				System.out.println("傳入序号有誤!!!");
			}
			// 關閉流
			dos.close();
			dis.close();
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
           
/**
 * 此類是服務端的上傳功能
 * @author PC
 */
public class SeverUpload {
	public void getServerUpload(DataInputStream dis, DataOutputStream dos) {
		try {
			// 接收用戶端傳過來的檔案姓名和大小
			String fileName = dis.readUTF();
			String length = dis.readUTF();
			System.out.println("fileName=" + fileName + "   length=" + length);
			// 建構本地輸出流
			DataOutputStream dos_local = new DataOutputStream(
					new BufferedOutputStream(new FileOutputStream("D:/download/" + fileName)));
			// 建立一個緩存
			byte[] buf = new byte[1024 * 4];
			int len = -1;
			while (true) {
				if (dis != null) {
					len = dis.read(buf);
				}
				if (len == -1) {
					break;
				}
				dos_local.write(buf, 0, len);
				dos_local.flush();
				System.out.println("傳輸中...");
			}
			dos_local.close();
			System.out.println("server傳輸完畢!!!");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
           
/**
 * 伺服器端的下載下傳
 * @author PC
 */
public class ServerDownload {
	public void getServerDownload(DataInputStream dis, DataOutputStream dos) {
		try {
			// 擷取用戶端傳過來的位址
			String filePath = dis.readUTF();
			// 尋找指定的檔案
			File file = new File(filePath);
			if (!file.exists()) {
				// 如果所找檔案不存在
				dos.writeUTF("請求檔案不存在,請重新輸入:");
				dos.flush();

			} else {
				// 檔案存在,那麼擷取檔案名和大小
				String fileName = file.getName();
				// 把檔案名稱寫到網絡上
				dos.writeUTF(fileName);
				dos.flush();
				// 把檔案大小寫到網絡上
				long length = file.length();
				dos.writeUTF(length + "");
				dos.flush();
				// 準備發送檔案
				System.out.println("準備發送檔案給...");
				// 建構本地輸入流
				DataInputStream dis_local = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
				// 建構緩沖
				byte[] buf = new byte[1024 * 4];
				int len = -1;
				// 将檔案讀到記憶體,在從記憶體寫到網絡上
				while (true) {
					if (dis_local != null) {
						// 讀到記憶體
						len = dis_local.read(buf);
					}
					if (len == -1) {
						break;
					}
					// 寫到網絡上
					dos.write(buf, 0, len);
					dos.flush();
					System.out.println("傳輸中...");
				}
				dis_local.close();
			}
			System.out.println("server傳輸完畢!!!");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

           
/**
 * 用戶端
 * @author PC
 */
public class Client {
	public static void main(String[] args) throws Exception {
		try {
			int i = 1;
			while (true) {
				// 建構Socket對象(Ip位址,端口号),相當于連接配接伺服器
				Socket socket = new Socket("localhost", 9991);
				// 建構網絡輸出流
				DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
				// 建構網絡輸入流
				DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
				Scanner input = new Scanner(System.in);
				System.out.println("請輸入要執行的操作的序号:1.下載下傳/2.上傳");
				String cz = input.next();
				// 把輸入的序号傳給服務端
				dos.writeUTF(cz);
				dos.flush();
				// 判斷序号是1.下載下傳還是2.上傳
				if (cz != null && "1".equals(cz)) {
					ClientDownload cd = new ClientDownload();
					cd.getClientDownload(dos, dis);
				} else if (cz != null && "2".equals(cz)) {
					ClientUpload cu = new ClientUpload();
					cu.getClientDownload(dos, dis);
				} else {

					System.out.println("輸入操作序号錯誤,請重新輸入:");
					if (i == 3) {
						System.out.println("三次錯誤!請重新開機!");
						break;
					}
					i++;
				}
				dis.close();
				dos.close();
				socket.close();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
           
/**
 * 此類寫用戶端的上傳功能
 * @author PC
 */
public class ClientUpload {
	public void getClientDownload(DataOutputStream dos, DataInputStream dis) {
		try {
			Scanner input = new Scanner(System.in);
			// 接收要上傳的檔案路徑
			System.out.println("請輸入要上傳的檔案路徑:");
			String filePath = input.next();
			File file = new File(filePath);
			if (!file.exists()) {
				System.out.println("檔案未找到");
			} else {
				// 把檔案名和檔案大小上傳
				String fileName = file.getName();
				dos.writeUTF(fileName);
				dos.flush();
				long length = file.length();
				dos.writeUTF(length + "");
				dos.flush();
				// 建構本地輸入流
				DataInputStream dis_local = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
				// 建立緩存
				byte[] buf = new byte[1024 * 4];
				int len = -1;
				System.out.println("檔案開始傳輸...");
				while (true) {
					if (dis_local != null) {
						len = dis_local.read(buf);
					}
					if (len == -1) {
						break;
					}
					dos.write(buf, 0, len);
					dos.flush();
					System.out.println("傳輸中...");
				}
				dis_local.close();
				System.out.println("client檔案傳輸完畢!!!");
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
           
/**
 * 此類寫用戶端的下載下傳
 * @author PC
 */
public class ClientDownload {
	public void getClientDownload(DataOutputStream dos, DataInputStream dis) {
		try {
			Scanner input = new Scanner(System.in);
			// 接收輸入的位址
			System.out.println("請輸入要下載下傳的檔案位址:");
			String filePath = input.next();
			// 把位址傳到網絡流
			dos.writeUTF(filePath);
			dos.flush();
			// 接收檔案的名字和大小
			String fileName = dis.readUTF();
			String length = dis.readUTF();
			System.out.println("檔案名字:" + fileName + "   length:" + length);
			// 建構本地輸出流
			DataOutputStream dos_local = new DataOutputStream(
					new BufferedOutputStream(new FileOutputStream("d:/download/" + fileName)));
			// 建構一個緩沖
			byte[] buf = new byte[1024 * 4];
			System.out.println("開始接收檔案...");
			int len = -1;
			// 循環從網絡上把資料讀入記憶體,再把記憶體檔案寫到硬碟
			while (true) {
				if (dis != null) {
					len = dis.read(buf);
				}
				if (len == -1) {
					break;
				}
				dos_local.write(buf, 0, len);
				dos_local.flush();
				System.out.println("檔案下載下傳中..");
			}
			dos_local.close();
			System.out.println("client檔案傳輸完畢!!!");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
           

繼續閱讀