springboot整合websocket实现复制目录进度推送
整体结构
后端(Java)
添加依赖
在你的pom.xml
文件中添加以下依赖:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter WebSocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
配置WebSocket
创建一个WebSocket配置类:
import com.small.demo.handler.MyWebSocketHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyWebSocketHandler(), "/progress").setAllowedOrigins("*");
}
}
创建WebSocket处理器
创建一个WebSocket处理器来处理消息:
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
public class MyWebSocketHandler extends TextWebSocketHandler {
private static final CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
}
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// Handle incoming messages if needed
}
public static void sendProgress(String progress) {
for (WebSocketSession session : sessions) {
try {
session.sendMessage(new TextMessage(progress));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
复制目录并发送进度
编写一个方法来复制目录并发送进度:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
public class FileCopyUtil {
public static void copyDirectoryWithProgress(File sourceDir, File targetDir) throws IOException {
if (!targetDir.exists()) {
targetDir.mkdirs();
}
List<File> filesToCopy = listFiles(sourceDir);
int totalFiles = filesToCopy.size();
int copiedFiles = 0;
for (File file : filesToCopy) {
File targetFile = new File(targetDir, file.getName());
copyFile(file, targetFile);
copiedFiles++;
int progress = (copiedFiles * 100) / totalFiles;
MyWebSocketHandler.sendProgress(LocalDateTime.now()+"===="+file.getName()+ "Progress: " + progress + "%");
}
}
private static List<File> listFiles(File dir) {
List<File> fileList = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
fileList.addAll(listFiles(file));
} else {
fileList.add(file);
}
}
}
return fileList;
}
private static void copyFile(File source, File target) throws IOException {
try (FileChannel sourceChannel = new FileInputStream(source).getChannel();
FileChannel targetChannel = new FileOutputStream(target).getChannel()) {
targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
}
}
}
控制器调用复制方法
创建一个控制器来触发复制操作
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.IOException;
@RestController
public class FileCopyController {
@GetMapping("/copy")
public String copyFiles(@RequestParam String sourcePath, @RequestParam String targetPath) {
new Thread(() -> {
try {
FileCopyUtil.copyDirectoryWithProgress(new File(sourcePath), new File(targetPath));
} catch (IOException e) {
e.printStackTrace();
}
}).start();
return "Copy started";
}
}
前端(JavaScript)
在前端,使用WebSocket连接并接收进度信息:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Copy Progress</title>
</head>
<body>
<div id="progress"></div>
<script>
const socket = new WebSocket('ws://localhost:8080/progress'); // 替换为你的WebSocket地址
socket.onmessage = function(event) {
document.getElementById('progress').innerText = event.data;
};
</script>
</body>
</html>
运行项目
启动Spring Boot应用程序,然后访问前端页面并触发文件复制操作。例如,通过浏览器访问http://localhost:8080/copy?sourcePath=/path/to/source&targetPath=/path/to/target
。你应该能够在前端看到实时的复制进度。