websocket推送进度条百分比给前台
Posted ジ绯色月下ぎ
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}
}
}
进度条进度数据 效果如下
以上是关于websocket推送进度条百分比给前台的主要内容,如果未能解决你的问题,请参考以下文章