依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>

config

  1. package com.example.logicbackfrontback.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  5. /**
  6. * WebSocket API 中,浏览器和服务器只需要做一个握手的动作,
  7. * 然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。HTML5
  8. * 义的 WebSocket 协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。
  9. */
  10. @Configuration
  11. public class WebSocketConfig {
  12. /**
  13. * ServerEndpointExporter 作用
  14. * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
  15. */
  16. @Bean
  17. public ServerEndpointExporter serverEndpointExporter() {
  18. return new ServerEndpointExporter();
  19. }
  20. }

model

  1. package com.example.logicbackfrontback.model.webSocket;
  2. import org.springframework.stereotype.Component;
  3. import javax.websocket.OnClose;
  4. import javax.websocket.OnMessage;
  5. import javax.websocket.OnOpen;
  6. import javax.websocket.Session;
  7. import javax.websocket.server.ServerEndpoint;
  8. import java.util.concurrent.CopyOnWriteArraySet;
  9. @Component
  10. @ServerEndpoint("/websocket")
  11. public class WebSocket {
  12. private Session session;
  13. private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
  14. private String msg = "0";
  15. @OnOpen
  16. public void onOpen(Session session) {
  17. this.session = session;
  18. webSockets.add(this);
  19. sendAllMessage(msg);
  20. }
  21. /**
  22. * 关闭调用方法
  23. */
  24. @OnClose
  25. public void onClose() {
  26. webSockets.remove(this);
  27. }
  28. @OnMessage
  29. public void onMessage(String msg) {
  30. }
  31. /**
  32. * 消息广播到前台
  33. *
  34. * @param msg
  35. */
  36. public void sendAllMessage(String msg) {
  37. for (WebSocket webSocket : webSockets) {
  38. try {
  39. webSocket.session.getBasicRemote().sendText(msg);
  40. } catch (Exception e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  45. }

controller

  1. package com.example.logicbackfrontback.controller;
  2. import com.example.logicbackfrontback.model.webSocket.WebSocket;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RequestMethod;
  6. import org.springframework.web.bind.annotation.RestController;
  7. @RestController
  8. public class ExportTxt {
  9. @Autowired
  10. private WebSocket websocket;
  11. @RequestMapping(value = "/test", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
  12. public void test(){
  13. String msg = "";
  14. int a = 0;
  15. for(int i=0;i<6;i++){
  16. msg = String.valueOf(a);
  17. websocket.sendAllMessage(msg);
  18. a=a+20;
  19. }
  20. }
  21. }

vue 前端

  1. <template>
  2. <div>
  3. <el-progress :percentage="percentMsg"></el-progress>
  4. <el-button @click="test">开始上传</el-button>
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. name: 'StartBack',
  10. props: ['mainData'],
  11. data () {
  12. return {
  13. percentMsg: 0
  14. }
  15. },
  16. mounted () {
  17. // WebSocket
  18. if ('WebSocket' in window) {
  19. this.websocket = new WebSocket('ws://localhost:8084/websocket')
  20. this.initWebSocket()
  21. } else {
  22. alert('当前浏览器 Not support websocket')
  23. }
  24. },
  25. methods: {
  26. test () {
  27. this.$axios.post(
  28. 'test',
  29. {}
  30. ).then(data => {
  31. console.log('================================')
  32. // eslint-disable-next-line handle-callback-err
  33. }).catch(error => {
  34. })
  35. },
  36. initWebSocket () {
  37. // 连接错误
  38. this.websocket.onerror = this.setErrorMessage
  39. // 连接成功
  40. this.websocket.onopen = this.setOnopenMessage
  41. // 收到消息的回调
  42. this.websocket.onmessage = this.setOnmessageMessage
  43. // 连接关闭的回调
  44. this.websocket.onclose = this.setOncloseMessage
  45. // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
  46. window.onbeforeunload = this.onbeforeunload
  47. },
  48. setErrorMessage () {
  49. console.log(
  50. 'WebSocket连接发生错误 状态码:' + this.websocket.readyState
  51. )
  52. },
  53. setOnopenMessage () {
  54. // console.log("WebSocket连接成功 状态码:" + this.websocket.readyState);
  55. },
  56. setOnmessageMessage (event) {
  57. console.log(false)
  58. // 服务器推送的消息
  59. console.log('服务端返回:' + event.data)
  60. // percentMsg就是绑定的进度值
  61. this.percentMsg = parseInt(event.data)
  62. if (this.percentMsg === 100) {
  63. // 如果进度是100 dialog框就隐藏
  64. this.dialogPortVisible = false
  65. }
  66. },
  67. setOncloseMessage () {
  68. // console.log("WebSocket连接关闭 状态码:" + this.websocket.readyState);
  69. },
  70. onbeforeunload () {
  71. this.closeWebSocket()
  72. },
  73. closeWebSocket () {
  74. this.websocket.close()
  75. },
  76. // format函数是和进度条组件绑定的 具体可查看element-ui组件官网进度条
  77. format (percentage) {
  78. return percentage === 100 ? '满' : `${percentage}%`
  79. }
  80. }
  81. }
  82. </script>