本文最后更新于:2022年12月19日 晚上
一个基于TCP的简单的文件上传程序
客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import java.io.*; import java.net.*; import java.util.Scanner;
public class LocalClient { public static void main(String[] args) throws IOException { String filePath; Scanner sc = new Scanner(System.in); System.out.println("输入要上传的文件地址:"); filePath = sc.nextLine(); FileInputStream fis = new FileInputStream(filePath); Socket socket = new Socket("127.0.0.1", 7222); OutputStream os = socket.getOutputStream(); byte[] bytes = new byte[1024]; int len = 0; while((len = fis.read(bytes)) != -1) { os.write(bytes, 0, len); } socket.shutdownOutput(); InputStream is = socket.getInputStream(); while((len = is.read(bytes)) != -1) { System.out.println(new String(bytes, 0, len)); } fis.close(); socket.close(); } }
|
服务端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| import java.io.*; import java.net.*; import java.util.Random; public class Server { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(7222); while (true) { Socket socket = server.accept(); new Thread(new Runnable() { @Override public void run() { try { InputStream is = socket.getInputStream(); File file = new File("C:\\UpdatePath"); if (!file.exists()) { file.mkdirs(); } String fileName = "File" + System.currentTimeMillis() + new Random().nextInt(99) + ".zip"; FileOutputStream fos = new FileOutputStream(file + "\\" + fileName); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { fos.write(bytes, 0, len); } OutputStream os = socket.getOutputStream(); os.write("Update complete! =w= ~".getBytes()); fos.close(); socket.close(); } catch (IOException e) { System.out.println(e); } } }).start(); } } }
|
以后有空可以再完善一下,识别上传文件的文件类型和文件名