TCP通讯协议,文件上传实现
//TCP通讯协议,服务端文件上传实现 public static void socketClient(File file) { try ( // 1. 创建流对象 // 1.1 创建输入流,读取本地文件 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); // 2. 创建客户端套接字,写出到服务端 // 2.1 创建客户端套接字 Socket socket = new Socket("localhost", 6666); // 2.2 创建输出流,写出到服务端 BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());) { // 3. 写出数据 byte[] bytes = new byte[8 * 1024]; int len; while ((len = bis.read(bytes)) != -1) { bos.write(bytes, 0, len); bos.flush(); } System.out.println("文件发送完毕!"); } catch (FileNotFoundException e1) { // TODO 日志 e1.printStackTrace(); } catch (IOException e2) { // TODO 日志 e2.printStackTrace(); } }
//TCP通讯协议,服务端文件上传实现 public static void socketServer(File file) { System.out.println("服务器启动......"); try ( //1. 创建服务端Socket ServerSocket serverSocket = new ServerSocket(6666); //2. 建立链接 Socket socketAccept = serverSocket.accept(); //3. 创建流对象 //3.1 获取输入流,读取文件数据 BufferedInputStream bis = new BufferedInputStream(socketAccept.getInputStream()); //3.2 创建输出流,保存到本地 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); ) { //4. 读写数据 byte[] bytes = new byte[8 * 1024]; int len; while((len = bis.read(bytes)) != -1) { bos.write(bytes, 0, len); } System.out.println("上传的文件已保存!"); } catch (IOException e) { // TODO 日志 e.printStackTrace(); } }
//测试 public static void main(String[] args) { File file = new File("D:\\demo\\TCP\\scoketServer.png"); socketServer(file); } File file = new File("D:/Downloads/壁纸/20200505.png"); socketClient(file);