SpringBoot整合WebSocket

  1. 引入依赖

    <!--websocket-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    
  2. 编写配置类

    /**
     * 开启WebSocket支持
     * @author: yww
     * @createTime: 2021/8/13
     */
    @Configuration
    public class WebSocketConfig {
    
        @Bean
        public ServerEndpointExporter serverEndpointExporter(){
            return new ServerEndpointExporter();
        }
    
    }
    
  3. 编写webSocket服务类

    /**
     * @author: yww
     * @createTime: 2021/8/13
     */
    @ServerEndpoint("/ws/{userId}")
    @Component
    public class WebSocketServer {
    
        private static  final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    
        /**
         * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象8
         */
        private static ConcurrentHashMap<String,WebSocketServer> clients = new ConcurrentHashMap<>();
        /**
         * 与某个客户端的连接会话,需要通过它来给客户端发送数据
         */
        private Session session;
        /**
         * 接收id
         */
        private String userId;
    
        /**
         * 开启连接
         * @param userId
         * @param session
         */
        @OnOpen
        public void onOpen(@PathParam("userId") String userId, Session session){
            log.info("连接建立: "+ userId);
            this.userId = userId;
            //判断该id是否已经加入,如果已经加入不重复加入
            if(!Share.isEmpty(userId)){
                this.session = session;
                clients.put(userId,this);
                log.info("现在连接的客户端 用户id为: "+userId);
    
                //新建连接,查询该连接用户id未读的消息
               /* HashMap<String, Object> map = new HashMap<>();
                map.put("userId",userId);
                map.put("status","0");
                sendMessageToUser(userId,nNoticeService.queryList(map));*/
            }
    
        }
    
        /**
         * 关闭连接
         */
        @OnClose
        public void onClose(){
            log.info("连接关闭");
        }
    
    
        /**
         * 接收消息
         * @param message
         * @param session
         */
        @OnMessage
        public void onMessage(String message, Session session){
            try{
                log.info("接收到消息:"+message+" 用户id为: "+this.userId);
                Thread.sleep(2000);
                session.getBasicRemote().sendText("收到了 "+this.userId+" 的消息");//发送消息
            }catch (IOException e){
                e.printStackTrace();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    
        /**
         * 连接错误
         * @param session
         * @param throwable
         */
        @OnError
        public void onError(Session session,Throwable throwable){
            throw new IllegalArgumentException(throwable);
        }
    
        /**
         * 向所有在线用户发送消息
         * @param message
         */
        public static void sendAllMessage(String message){
            clients.forEach((k,v) ->{
                try {
                    v.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    
        /**
         * 向指定用户发送消息
         * @param userId
         * @param message
         */
        public static void sendMessageToUser(String userId,String message){
            clients.forEach((k,v) ->{
                if(clients.get(userId) == null){
                    log.error("接收消息对象未上线!!!");
                }else{
                    if(k.equals(userId)){
                        try {
                            v.sendMessage(message);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    
        /**
         * 向指定用户发送消息
         * @param userId
         * @param object
         */
        public static void sendMessageToUser(String userId,Object object){
            clients.forEach((k,v) ->{
                if(clients.get(userId) == null){
                    log.error("接收消息对象未上线!!!");
                }else{
                    if(k.equals(userId)){
                        try {
                            v.sendMessage(object);
                        } catch (IOException | EncodeException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    
    
        /**
         * 发送消息
         * @param object
         * @throws IOException
         * @throws EncodeException
         */
        public void sendMessage(Object object) throws IOException, EncodeException {
    
            //异步发送消息
            //this.session.getAsyncRemote().sendObject(object);
            //同步发送消息
            this.session.getBasicRemote().sendObject(object);
        }
    
        /**
         * 发送消息
         * @param message
         * @throws IOException
         */
        public void sendMessage(String message) throws IOException{
            this.session.getBasicRemote().sendText(message);
        }
    }
    
  4. 前端测试

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
          th:with="unixstamp=${#dates.createNow().time}">
    <!--引用头部-->
    <div th:include="common/common :: common"></div>
    <head>
        <meta charset="UTF-8">
        <title>websocket测试</title>
    </head>
    <body>
    <div style="text-align: center">
        <div id="content"></div>
        <input type="text" class="msg"/><br/>
        <input type="button" value="发送" onclick="sendMessage()"/><br/>
        <input type="button" value="关闭websocket" onclick="sock.close()"/>
    </div>
    
    <!--websocket-->
    <script>
        var url=null;
        var sock=null;
        var userId = "user001";
        // var userName=getQueryString("userName")
        //百度来的函数,用来截取参数
        $(function(){
            if(!window.WebSocket){
                alert('你的浏览器不支持WebSocket');
            }else{
                url='ws://localhost:8011/shopping/ws/'+userId
                sock=new WebSocket(url)
                sock.onopen=function () {
                    $("#content").append("<h1>欢迎"+userId+"来到聊天室</h1>");
                }
                sock.onmessage=function (e) {
                    $("#content").append("<p>"+e.data+"</p>")
                }
                sock.onclose=function () {
                    window.close();
                }
            }
        });
    
        function sendMessage() {
            var date=new Date()
            sock.send(userId+" "+date.toLocaleTimeString()+" 说<br/>"+$('.msg').val())
            $('.msg').val("")
        }
    
    </script>
    
    </body>
    </html>
    
  5. 向指定用户发送消息

    @RequestMapping("/list.html")
        public String list(){
            //向指定用户发送消息
            WebSocketServer.sendMessageToUser("1","hello,我 是 admin!");
            return "web/websocket/websocketList";
        }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Spring Boot整合WebSocket,你需要进行以下步骤: 1. 首先,在pom.xml文件中添加WebSocket的相关依赖。可以使用以下两个依赖之一: - 从中提到的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` - 从中提到的依赖: ```xml <!--webSocket--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 创建WebSocket配置类,这个类负责配置WebSocket的相关信息。你可以按照以下方式创建一个配置类[3]: ```java package com.loit.park.common.websocket; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } } ``` 3. 至此,你已经完成了WebSocket整合配置。现在,你可以在你的应用中创建WebSocket的控制器并定义你的WebSocket端点。你可以根据你的需求来实现WebSocket端点的业务逻辑。 这就是Spring Boot整合WebSocket的基本步骤。通过这种方式,你可以在Spring Boot应用中轻松地使用WebSocket进行实时通信。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [springboot整合websocket](https://blog.csdn.net/weixin_45390688/article/details/120448778)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [springboot整合websocket(详解、教程、代码)](https://blog.csdn.net/hjq_ku/article/details/127503180)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值