• springboot 集成webSocket


    1、什么是webSocket?

    WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

    1.新建config包,创建WebSocketConfig类

    @Configuration
    public class WSConfiguration {
        @Bean
        public ServerEndpointExporter serverEndpointExporter(){
            return new ServerEndpointExporter();
        }
    }
    ​

    2.新建service包,创建WebSocketServer类

    @Component
    @ServerEndpoint("/websocket")
    public class WebSocketServer {
        //准备一个内部安全的集合 存放所有用户的websocket服务
        private static CopyOnWriteArraySet wsset =  new CopyOnWriteArraySet<>();
        private Session session;
        @OnOpen
        public void opOpen(Session session){
            this.session=session;
            //将自身填充到set集合中 这个集合是所有客户端websocket的集合
    ​
            wsset.add(this);
            sendMsg();
    ​
    ​
        }
        @OnClose
        public void onClose(){
            //将自己从set集合中删除
             wsset.remove(this);
        }
        @OnError
        public void onError(Session session,Throwable error){
            System.out.println(this+"发生错误了");
        }
    ​
        //客户端发来消息
        @OnMessage
        public void onMessage(String clientMsg, Session session){
            System.out.println("来自客户端的信息+“。。。。。。。。。”===》"+clientMsg);
            //每隔一秒给你推送一条当前时间信息
    ​
        }
    ​
        private void sendMsg(){
    ​
            try {
                while(true){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String time =sdf.format(new Date());
                    //发送数据
                    this.session.getBasicRemote().sendText(time);
                    Thread.sleep(1000);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    ​
    ​
    }
    ​

    3.controller层加注解

    @SpringBootApplication
    @EnableWebSocket
    public class MywebsocketApplication {
    ​
        public static void main(String[] args) {
            SpringApplication.run(MywebsocketApplication.class, args);
        }
    ​
    }
    ​

    4在resources下编写HTMl

    
        
        
        
            
    ​       ​   ​

    5网页访问

    http://localhost:8080/

    6 WebSocketServer同步发送消息

    package com.kgc.mywebsocket.commons;
    ​
    import org.springframework.stereotype.Component;
    import org.springframework.stereotype.Service;
    ​
    import javax.websocket.*;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.concurrent.CopyOnWriteArrayList;
    import java.util.concurrent.CopyOnWriteArraySet;
    @Component
    @ServerEndpoint("/websocket")
    public class WebSocketServer {
        //准备一个内部安全的集合 存放所有用户的websocket服务
        private static CopyOnWriteArraySet wsset =  new CopyOnWriteArraySet<>();
        private Session session;
        @OnOpen
        public void opOpen(Session session){
            this.session=session;
            //将自身填充到set集合中 这个集合是所有客户端websocket的集合
    ​
            wsset.add(this);
    //        sendMsg();
    ​
    ​
        }
        @OnClose
        public void onClose(){
            //将自己从set集合中删除
             wsset.remove(this);
        }
        @OnError
        public void onError(Session session,Throwable error){
            System.out.println(this+"发生错误了");
        }
    ​
        //客户端发来消息
        @OnMessage
        public void onMessage(String clientMsg, Session session){
            System.out.println("来自客户端的信息+“。。。。。。。。。”===》"+clientMsg);
            //每隔一秒给你推送一条当前时间信息
            sendAllClient(clientMsg);
    ​
        }
    ​
        private void sendMsg(){
    ​
            try {
                while(true){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String time =sdf.format(new Date());
                    //发送数据
                    this.session.getBasicRemote().sendText(time);
                    Thread.sleep(1000);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    ​
        private void sendAllClient(String msg){
            try {
                for(WebSocketServer wss:wsset){
                    wss.session.getBasicRemote().sendText(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    ​

    7 html同步发送消息

    
    
        
        
        
            
          ==========             ==========      
               
          ​   ​
    http://localhost:8080/
    

  • 相关阅读:
    部署jenkins,结合gitlab实现jva自动化部署
    JS 上传图片转换base64字符串&与Blob对象互转&图片下载
    python小技巧:创建单链表及删除元素
    正态分布的概率密度函数|正态分布检验|Q-Q图
    C++笔记之文档术语——将可调用对象作为函数参数
    mac 安装allure
    vue 实现自定义分页打印 window.print
    蓝桥杯每日一题2023.11.13
    Android Poco初始化时,不大起眼但可能存在坑点的参数们
    基于JavaSwing开发帐号管理系统+报告 课程设计 大作业源码
  • 原文地址:https://blog.csdn.net/just_learing/article/details/125899260