websocket推送进度条百分比给前台
说明:后台springboot项目 前台vue+element-UI
直接放代码:
//别忘了开启springboot的websocket <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
首先在启动类中注入
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
@Component
@ServerEndpoint("/websocket")
public class WebSocket {
private Session session;
private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
private String msg = "0";
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSockets.add(this);
sendAllMessage(msg);
}
/**
* 关闭调用方法
*/
@OnClose
public void onClose() {
webSockets.remove(this);
}
@OnMessage
public void onMessage(String msg) {
}
/**
* 消息广播到前台
*
* @param msg
*/
public void sendAllMessage(String msg) {
for (WebSocket webSocket : webSockets) {
try {
webSocket.session.getBasicRemote().sendText(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//前台vue
//前台js mounted是vue用来初始化的 methods里定义的是方法
//后台调用推送数据
@RestController
public class ExportTxt {
@Autowired
private WebSocket websocket;
@RequestMapping(value = "/test", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
public void test(){
String msg = "";
int a = 0;
for(int i=0;i<5;i++){
msg = String.valueOf(a);
websocket.sendAllMessage(msg);
a=a+20;
}
}
}
进度条进度数据 效果如下