美文网首页SpringbootjavaWeb学习管理后台系统
springboot+vue 使用websocket后台主动向前

springboot+vue 使用websocket后台主动向前

作者: 包袱雄狮 | 来源:发表于2020-09-23 18:00 被阅读0次

    前提

         本篇文章适用于入门级别,不做深入研究。
    

    后台springboot代码

    引入依赖

            <!--websocket-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-websocket</artifactId>
            </dependency>
    

    配置类

    @Configuration
    public class CommonConfig {
    
        /**
         * websocket配置
         * @return
         */
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    }
    

    websocket服务类

    @ServerEndpoint("/websocket/{username}")
    @Slf4j
    @Component
    public class Websocket {
        //静态变量,用来记录当前在线连接数。设计为安全的
        private static int onlineCount = 0;
        //concurrentHashMap分段锁,用来存放每个客户端对应的Websocket对象。
        private static Map<String, Websocket> clients = new ConcurrentHashMap<String, Websocket>();
        //与某个客户端的连接会话,需要通过它来给客户端发送数据
        private Session session;
        private String username;
    
        /**
         * 连接建立成功调用的方法
         * @param username
         * @param session
         */
        @OnOpen
        public void onOpen(@PathParam("username") String username, Session session) {
            this.username = username;
            this.session = session;
            Websocket.onlineCount++;
            log.info("有一连接进入!当前在线人数为" + onlineCount);
            clients.put(username, this);
        }
    
        /**
         * 连接关闭调用的方法
         */
        @OnClose
        public void onClose() {
            clients.remove(username);
            Websocket.onlineCount--;
            log.info("有一连接关闭!当前在线人数为" + onlineCount);
    
        }
    
        /**
         * 收到客户端消息后调用的方法
         * @param message
         */
        @OnMessage
        public void onMessage(String message) {
            System.out.println("收到客户端的消息"+message);
            sendMessage(message);
        }
    
        @OnError
        public void onError(Session session, Throwable throwable) {
            log.error("WebSocket发生错误:" + throwable.getMessage());
        }
    
        public static void sendMessage(String message) {
            // 向所有连接websocket的客户端发送消息
            // 可以修改为对某个客户端发消息
            for (Websocket item : clients.values()) {
                item.session.getAsyncRemote().sendText(message);
            }
        }
    }
    

    测试请求方法

    @RestController
    @RequestMapping("/news")
    public class NewsController {
    
        @GetMapping("/send")
        public String send(){
            Websocket.sendMessage("这是websocket群发消息!");
            return "发送消息成功";
        }
    
    }
    

    前端VUE

    这是在创建vue项目自带的HelloWorld.vue文件里修改的

    <template>
      <div class="hello">
        <h1>测试webSocket</h1>
      </div>
    </template>
    
    <script>
    export default {
      name: 'HelloWorld',
      props: {
        msg: String
      },
    
      created() { // 页面创建生命周期函数
        this.initWebSocket()
      },
      destroyed: function () { // 离开页面生命周期函数
        this.websocketclose();
      },
      methods: {
        initWebSocket: function () {
          // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
          this.websock = new WebSocket("ws://127.0.0.1:8031/websocket/test");
          this.websock.onopen = this.websocketonopen;
          this.websock.onerror = this.websocketonerror;
          this.websock.onmessage = this.websocketonmessage;
          this.websock.onclose = this.websocketclose;
        },
        websocketonopen: function () {
          console.log("WebSocket连接成功");
        },
        websocketonerror: function () {
          console.log("WebSocket连接发生错误");
        },
        websocketonmessage: function (e) {
          console.log(e.data);                // console.log(e);
        },
        websocketclose: function (e) {
          console.log("connection closed (" + e.code + ")");
        }
    
      }
    }
    </script>
    
    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style scoped>
    h3 {
      margin: 40px 0 0;
    }
    ul {
      list-style-type: none;
      padding: 0;
    }
    li {
      display: inline-block;
      margin: 0 10px;
    }
    a {
      color: #42b983;
    }
    </style>
    

    测试

    OK!代码部分已结束,现在先启动后台springboot,和前端vue。打开页面按下F12看日志打印。


    image.png

    非常好,这时候说明前后端websocket已经连接成功了。
    下面用你的工具(http测试工具,postman之类的)测试推送消息接口。

    image.png

    很棒,调用接口成功,信息成功发送。下面看看前端是否收到。

    image.png

    OK!大功告成!各位朋友!
    good luck!
    后会有期!

    有什么问题也可以私信我或评论,看到就会回复。

    相关文章

      网友评论

        本文标题:springboot+vue 使用websocket后台主动向前

        本文链接:https://www.haomeiwen.com/subject/vkpoyktx.html