springboot 集成 websocket

1.介绍

WebSocket是HTML5新增的协议,它的目的是在浏览器和服务器之间建立一个不受限的双向通信的通道。实时推送数据/通知到浏览器

方法一

  1. 引入WebSocket依赖包
    ````xml

    org.springframework.boot
    spring-boot-starter-websocket

    org.springframework.boot
    spring-boot-starter-webflux

  2. 编写 WebSocket 实现方法
    @ServerEndpoint(value = "/websocket/{id}")
    @Component
    public class WebSocketServer {
    
        /**
         * 静态常量,记录连接个数,线程安全
         */
        private static int onlineCount = 0;
    
        /**
         * 存放客户端对应的WebSocket对象
         */
        private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    
        /**
         * 会话信息
         */
        private Session session;
    
        @OnOpen
        public void onOpen(Session session){
            this.session = session;
            webSocketSet.add(this);
            addOnlineCount();
            try {
                sendMessage("连接成功");
            }catch (IOException ex){
                System.out.println(ex.getMessage());
            }
        }
    
        @OnMessage
        public void onMessage(String message, Session session, @PathParam("id")String id){
            System.out.println("来自客户端的消息:" + message);
    
            //群发消息
            for (WebSocketServer item : webSocketSet) {
                try {
                    item.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        @OnClose
        public void onClass(){
            webSocketSet.remove(this);
            subOnlineCount();
            System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
        }
    
        @OnError
        public void onError(Session session,Exception ex){
            ex.printStackTrace();
        }
    
        /**
         * 发送消息
         * @param message
         * @throws IOException
         */
        private void sendMessage(String message) throws IOException {
            this.session.getBasicRemote().sendText(message);
        }
    
        private void sendInfo(String message){
            System.out.println(message );
            for (WebSocketServer item:webSocketSet ) {
    
                try{
                    item.sendMessage(message);
                }catch (IOException ex){
                    System.out.println(ex.getMessage());
    
                }
            }
        }
    
        private synchronized void addOnlineCount(){
            WebSocketServer.onlineCount ++;
        }
    
        private synchronized void subOnlineCount(){
            WebSocketServer.onlineCount --;
        }
    
        public static synchronized long getOnlineCount(){
            return WebSocketServer.onlineCount;
        }
    }
    
  3. 添加配置文件
    ````java
    @Configuration
    public class WebSocketConfig {

     @Bean
     public ServerEndpointExporter serverEndpointExporter() {
         return new ServerEndpointExporter();
     }

    }

####方法二

  1. 编写消息处理类
public class WebSocketMessageHandler extends TextWebSocketHandler {

 /**
  * 静态常量,保存连接数量,线程安全
  */
 private static long onlineCount = 0;

 /**
  * 保存客户端信息
  */
 private static CopyOnWriteArraySet<WebSocketSession> webSocketSet = new CopyOnWriteArraySet();

 /**
  * 会话信息
  */
 private WebSocketSession session;

 public WebSocketMessageHandler(){
     super();
 }

 /**
  * 连接建立之后
  * @param session
  * @throws Exception
  */
 public void afterConnectionEstablished(WebSocketSession session) throws Exception{
     this.session = session;
     webSocketSet.add(session);
     addOnlineCount();
     System.out.println("连接成功,当前连接数:"+getOnlineCount());
 }

 /**
  * 处理收到的websocket信息
  */
 @Override
 protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
     String payload = message.getPayload();
     System.out.println("sadddddd");
     sendMessage(payload);
 }

 public void handleTransportError(WebSocketSession session, Throwable var2) throws Exception{

 }

 public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception{
    webSocketSet.remove(session);
     subOnlineCount();
     System.out.println("连接断开,当前连接数:"+getOnlineCount());

 }

 private void sendMessage(String message)  throws IOException {
     for (WebSocketSession session: webSocketSet ) {
         session.sendMessage(new TextMessage( message));
     }
 }

 ///////
 private synchronized void addOnlineCount(){

     onlineCount++;
 }
 private synchronized void subOnlineCount(){

     onlineCount--;
 }
 private synchronized long  getOnlineCount(){

     return this.onlineCount;
 }
}
  1. 位置文件

@Configuration
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry.addHandler(handler(),"/notice/{id}")//访问地址
        .setAllowedOrigins("*");///解决跨域问题
    }

    public WebSocketHandler handler(){
        return  new WebSocketMessageHandler();
    }
}

总结

1.网上找资料按照第一种实现,结果总是报错,比较靠谱的解释是aop拦截问题,使得ServerEndpointExporter
注册不进去;

2.第二种方法有效,一定不要忘记加依赖文件

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

原文地址:https://www.cnblogs.com/monkay/p/11130255.html

时间: 2024-08-30 18:17:09

springboot 集成 websocket的相关文章

springboot集成websocket的两种实现方式

WebSocket跟常规的http协议的区别和优缺点这里大概描述一下 一.websocket与http http协议是用在应用层的协议,他是基于tcp协议的,http协议建立链接也必须要有三次握手才能发送信息.http链接分为短链接,长链接,短链接是每次请求都要三次握手才能发送自己的信息.即每一个request对应一个response.长链接是在一定的期限内保持链接.保持TCP连接不断开.客户端与服务器通信,必须要有客户端发起然后服务器返回结果.客户端是主动的,服务器是被动的. WebSocke

springboot集成websocket

websocket是全双工通信协议,目前html5支持,如果是app端的话可能不支持,建议app端实现通过tcp握手长连接实现通信,这里暂不研究. 首先websocket是一个协议,需要了解一下 第一步先引入starter 1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-websocket</artifactId

SpringBoot之集成WebSocket

websocket是什么不做介绍.开发环境:jdk1.8,win7_64旗舰版,idea 1.初始化一个springboot项目 2.加入websocket依赖 <!-- springboot的websocket依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactI

springBoot 使用webSocket

本文(2019年6月18日 飞快的蜗牛博客) 有许多人走着走着,就迷失了自己,所以不论发生了什么,有时候抱着自己去静下来想想,要好好的对待自己:“钱塘江上潮信来,今日方知我是我”,我信奉这句话,不是我超脱了,是有时我们醒悟了: 注意标题:springboot使用websocket 1]第一步:引入依赖: <!--集成websocket--> <dependency> <groupId>org.springframework.boot</groupId> &l

SpringBoot集成MyBatis的分页插件PageHelper

俗话说:好??不吃回头草,但是在这里我建议不管你是好马还是不好马,都来吃吃,带你复习一下分页插件PageHelper. 昨天给各位总结了本人学习springboot整合mybatis第一阶段的一些学习心得和源码,主要就算是敲了一下SpringBoot的门儿,希望能给各位的入门带给一点儿捷径,今天给各位温习一下MyBatis的分页插件PageHelper和SpringBoot的集成,它的使用也非常简单,开发更为高效.因为PageHelper插件是属于MyBatis框架的,所以相信很多哥们儿都已经用

springboot集成swagger2构建RESTful API文档

在开发过程中,有时候我们需要不停的测试接口,自测,或者交由测试测试接口,我们需要构建一个文档,都是单独写,太麻烦了,现在使用springboot集成swagger2来构建RESTful API文档,可以在访问接口上,直接添加注释 先介绍一下开发环境: jdk版本是1.8 springboot的版本是1.4.1 开发工具为 intellij idea 我们先引入swagger2的jar包,pom文件引入依赖如下: <dependency> <groupId>io.springfox&

spring-boot集成Springfox-Swagger2

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documenta

【spring-boot】spring-boot集成ehcache实现缓存机制

EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. ehcache提供了多种缓存策略,主要分为内存和磁盘两级,所以无需担心容量问题. spring-boot是一个快速的集成框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. 由于spring-boot无需任何样板化的配置文件,所以spring-boot集成一些其他框架时会有略微的

SpringBoot集成MyBatis的分页插件PageHelper(回头草)

俗话说:好??不吃回头草,但是在这里我建议不管你是好马还是不好马,都来吃吃,带你复习一下分页插件PageHelper. 昨天给各位总结了本人学习springboot整合mybatis第一阶段的一些学习心得和源码,主要就算是敲了一下SpringBoot的门儿,希望能给各位的入门带给一点儿捷径,今天给各位温习一下MyBatis的分页插件PageHelper和SpringBoot的集成,它的使用也非常简单,开发更为高效.因为PageHelper插件是属于MyBatis框架的,所以相信很多哥们儿都已经用