SpringBoot整合WebSocket

SpringBoot整合WebSocket

1.简介

在WebSocket之前想要实现即时的通信效果,往往采用定时轮询AJAX发送HTTP请求来实现的,这种方式会导致网络带宽的浪费,多次请求的实时性也不高,频繁的建立和断开连接也会占用CPU资源,造成不必要的浪费

WebSocket的出现解决了上述问题,WebSocket是一个基于TCP实现的一个全双工通信协议,通过一次请求建立一个长效的连接

  • 头部数据较少,可以节省带宽
  • 通过建立一个长连接来实现是即时通信

在这里插入图片描述

2.应用场景

  1. 体育实况更新
  2. 视频弹幕
  3. 定位软件
  4. 股票大屏
  5. 协同编辑

3.maven坐标

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

4.整合

首先创建一个配置类
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}
接着,开始写websocket的处理逻辑
@Component
@Slf4j
@ServerEndpoint("/websocket/{userId}")
public class WsService {
    //与某个客户端的连接会话,通过session向客户端发送数据
    private Session session;

    //当前在线用户数量
    private static int onlineCount = 0;

    private String userId;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WsService> webSockets =new CopyOnWriteArraySet<>();
    // 用来存在线连接用户信息
    private static ConcurrentHashMap<String,WsService> webSocketMap  = new ConcurrentHashMap<String,WsService>();

    /*
    * 建立连接调用的方法
    * */
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) throws IOException {
        this.session=session;
        this.userId=userId;

        if (!webSocketMap.containsKey(userId)){
            webSocketMap.put(userId,this);
            addOnlineCount();
        }
        log.info("用户连接:"+userId+",当前在线人数为:"+getOnlineCount());
        sendMessage("连接成功");


    }

    /*
    * 连接关闭调用的方法
    * */
    @OnClose
    public void onClose(){
        if (webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            subOnlineCount();
        }
        log.info("用户退出:"+userId+",当前在线人数为:"+getOnlineCount());
    }

    /*
    * 收到客户端消息调用的方法
    * */
    @OnMessage
    public void onMessage(String message,Session session){
        log.info("【webSocket消息】收到客户端发来的消息:{}",message);
    }


    @OnError
    public void onError(Session session,Throwable error){
        log.error("用户错误:"+userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }

    /*
    * 服务端主动发送消息
    * */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /*
    * 发送自定义消息
    * */
    public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
        log.info("发送消息到:"+userId+",报文:"+message);
        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage(message);
        }else {
            log.error("用户:"+userId+",不在线!");
        }
    }



    public static synchronized void addOnlineCount(){
        onlineCount++;
    }

    public static synchronized  int getOnlineCount(){
        return onlineCount;
    }

    public static synchronized  void subOnlineCount(){
        onlineCount--;
    }
}
tOnlineCount(){
        return onlineCount;
    }

    public static synchronized  void subOnlineCount(){
        onlineCount--;
    }
}
  • 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、付费专栏及课程。

余额充值