【Java】TCP:文件上传
需求
使用网络编程,通过TCP实现文件上传
步骤
- 服务端
- 建立连接
- 等待客户端连接
- 接收文件
- 获取输入流
- 文件输出
- 接收完毕通知客户端
- 关闭资源
- 客户端
- 创建连接
- 获取文件
- 创建输出流
- 读取文件
- 写入文件
- 传输完毕,通知服务器
- 确认服务器接收完毕
- 关闭流
- 启动
- 启动服务器
- 启动客户端
代码
-
服务端
package TCP.fileUpload; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.Scanner; public class FileUploadServer { public static void main(String[] args) throws IOException { // 1. 建立连接 ServerSocket serverSocket = new ServerSocket(6060); // 2. 等待客户端连接 Socket socket = serverSocket.accept(); // 3. 接收文件 //获取输入流 InputStream is = socket.getInputStream(); //文件输出 FileOutputStream fos = new FileOutputStream(new File("src/TCP/fileUpload/receiveFile")); byte[] bytes = new byte[1024]; int len; while ((len = is.read(bytes)) != -1){ fos.write(bytes,0,len); } // 4. 接收完毕,通知客户端 OutputStream os = socket.getOutputStream(); os.write("上传成功".getBytes(StandardCharsets.UTF_8)); // 5. 关闭资源 if (fos != null) fos.close(); if (is != null) is.close(); if (socket != null) socket.close(); if (serverSocket != null) serverSocket.close(); } }
-
客户端
package TCP.fileUpload; import java.io.*; import java.net.InetAddress; import java.net.Socket; public class FileUploadClient { public static void main(String[] args) throws IOException { //1. 创建连接 Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 6060); //2. 创建输出流,读取并写入文件 OutputStream os = socket.getOutputStream(); FileInputStream fis = new FileInputStream(new File("src/TCP/fileUpload/fileUpload.txt")); byte[] bytes = new byte[1024]; int len; while ((len = fis.read(bytes)) != -1){ os.write(bytes,0,len); } //3. 通知服务器传输完成 socket.shutdownOutput(); //4. 确定服务器接收完毕 InputStream is = socket.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); //管道流 byte[] b = new byte[1024]; int l; while ((l = is.read(b)) != -1){ baos.write(b,0,l); } System.out.println(baos.toString()); //5. 关闭流 if (baos != null) baos.close(); if (is != null) is.close(); if (fis != null) fis.close(); if (os != null) os.close(); if (socket != null) socket.close(); } }