当前位置: 首页 > news >正文

Springboot整合WebScoket

目录

WebSocketServer

消息推送

建立websocket连接

运行结果


WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。websocket 协议是在 http 协议上的一种补充协议,是 html5 的新特性,是一种持久化的协议。

基于Tcp三次握手?

第一次握手:

客户主动(active open)去connect服务器,并且发送SYN,假设序列号为J,服务器是被动打开(passive open)

第二次握手:

服务器在收到SYN后,它会发送一个SYN以及一个ACK(应答)给客户, ACK的序列号是J+1,表示是给SYN J的应答,新发送的SYN K序列号是K。

第三次握手:
客户在收到新SYN K、ACK J+1后,也回应ACK K+1以表示收到了,然后两边就可以开始发送数据了

案例

添加pom依赖

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

websocket配置

/**
 * 开启WebSocket支持
 *
 */
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {

        return new ServerEndpointExporter();
    }
}

WebSocketServer

下面是websocket的重点

1.@ServerEndpoint("/api/pushMessage/{userId}") 前端通过此 URI 和后端交互,建立连接
2.@Component 不用说将此类交给 spring 管理
3.@OnOpen websocket 建立连接的注解,前端触发上面 URI 时会进入此注解标注的方法
4.@OnMessage 收到前端传来的消息后执行的方法
5.@OnClose 顾名思义关闭连接,销毁 session
60因为WebSocket是类似客户端服务端的形式(采用ws协议),那么这里的WebSocketServer其实就相当于一个ws协议的Controller
7.新建一个ConcurrentHashMap webSocketMap 用于接收当前userId的WebSocket,方便IM之间对userId进行推送消息
 

核心代码如下

 

/**
 * websocket的处理类。
 * 作用相当于HTTP请求
 * 中的controller
 */
@Component
@Slf4j
@ServerEndpoint("/api/pushMessage/{userId}")
public class WebSocketServer {

    /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set,用来存放每个客户端对应的WebSocket对象。*/
    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId = "";

    /**
     * 连接建立成
     * 功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {
        this.session = session;
        this.userId=userId;
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //加入set中
            webSocketMap.put(userId,this);
        }else{
            //加入set中
            webSocketMap.put(userId,this);
            //在线数加1
            addOnlineCount();
        }
        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());
        sendMessage("连接成功");
    }

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

    /**
     * 收到客户端消
     * 息后调用的方法
     * @param message
     * 客户端发送过来的消息
     **/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:"+userId+",报文:"+message);
        //可以群发消息
        //消息保存到数据库、redis
        if(StringUtils.isNotBlank(message)){
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("fromUserId",this.userId);
                String toUserId=jsonObject.getString("toUserId");
                //传送给对应toUserId用户的websocket
                if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
                    webSocketMap.get(toUserId).sendMessage(message);
                }else{
                    //否则不在这个服务器上,发送到mysql或者redis
                    log.error("请求的userId:"+toUserId+"不在该服务器上");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务
     * 器主动推送
     */
    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

    /**
     * 获得此时的
     * 在线人数
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 在线人
     * 数加1
     */
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    /**
     * 在线人
     * 数减1
     */
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

}

消息推送

至于推送新信息,可以在自己的Controller写个方法调用WebSocketServer.sendInfo()即可。
程序中使用定任务不停的向客户端发送消息。

@Controller
@RequestMapping("/api/test")
@Api(description = "服务器向客户端推送消息接口", tags = "Test")
public class TestController {

    @Autowired
    private TestServiceImpl testServiceImpl;
    /**
     * 启动页面
     * @return
     */
    @GetMapping("/start")
    public String start(){
        return "index";
    }

    @PostMapping("/pushToWeb")
    @ApiOperation(value = "服务器端向客户端推送消息", notes = "服务器端向客户端推送消息")
    public ResponseBean<?> pushToWeb(@RequestBody @ApiParam(value = "回收人编码和医院编码", required = true) CodesInfo info){

        testServiceImpl.printTime();
        return new ResponseBean<>(200, "success", "123456");
    }

}

@Service
@EnableScheduling
public class TestServiceImpl {

    //打印时间
    @Scheduled(fixedRate=1000) //1000毫秒执行一次
    public  void  printTime(){

        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        String date = dateFormat.format(new Date());
        WebSocketServer.sendInfo(date,"10");
        System.out.println(date);
    }

}

建立websocket连接

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket通讯</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    let socket;
    function openSocket() {

        const socketUrl = "ws://localhost:9091/api/pushMessage/" + $("#userId").val();
        console.log(socketUrl);
        if(socket!=null){
            socket.close();
            socket=null;
        }
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function() {
            console.log("websocket已打开");
        };
        //获得消息事件
        socket.onmessage = function(msg) {
            console.log(msg.data);
            //发现消息进入,开始处理前端触发逻辑
        };
        //关闭事件
        socket.onclose = function() {
            console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            console.log("websocket发生了错误");
        }
    }
    function sendMessage() {

        socket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
        console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
    }
</script>
<body>
<p>【socket开启者的ID信息】:<div><input id="userId" name="userId" type="text" value="10"></div>
<p>【客户端向服务器发送的内容】:<div><input id="toUserId" name="toUserId" type="text" value="20">
    <input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【操作】:<div><a onclick="openSocket()">开启socket</a></div>
<p>【操作】:<div><a onclick="sendMessage()">发送消息</a></div>
</body>

</html>

运行结果

服务器端向客户端发送消息

 

 

 

相关文章:

  • 小学生的护眼灯哪个品牌最好?分享学生护眼台灯品牌
  • 使用docker快速安装开发环境
  • Spring boot发布到k8s并加载Configmap配置文件,实现配置热更新
  • 3号截止?2022年成都市市级创业孵化基地申报认定要求、材料及时间
  • php://input、php://output 区别及用法
  • 基于Springboot+vue的箱包销售商城网站 elementui
  • SpringCloud-zuul
  • TVS 管选型与 ESD 防护设计
  • 股票量化交易系统的指标和策略有哪些?
  • nnUnet代码分析一训练
  • 节约用水也有钱?成都市2022年成都市节约用水申报奖励、条件、材料、时间及流程
  • 计算机网络——层次结构
  • [Android]Android P(9) WIFI学习笔记 - 扫描 (1)
  • java众筹网计算机毕业设计MyBatis+系统+LW文档+源码+调试部署
  • .NET BackgroundWorker
  • 【Leetcode】101. 对称二叉树
  • [LeetCode] Wiggle Sort
  • 30天自制操作系统-2
  • Druid 在有赞的实践
  • Javascripit类型转换比较那点事儿,双等号(==)
  • mac修复ab及siege安装
  • win10下安装mysql5.7
  • 订阅Forge Viewer所有的事件
  • 和 || 运算
  • 基于阿里云移动推送的移动应用推送模式最佳实践
  • 解析带emoji和链接的聊天系统消息
  • 使用Maven插件构建SpringBoot项目,生成Docker镜像push到DockerHub上
  • Nginx惊现漏洞 百万网站面临“拖库”风险
  • 直播平台建设千万不要忘记流媒体服务器的存在 ...
  • #NOIP 2014# day.1 T2 联合权值
  • #我与Java虚拟机的故事#连载03:面试过的百度,滴滴,快手都问了这些问题
  • (day 2)JavaScript学习笔记(基础之变量、常量和注释)
  • (LNMP) How To Install Linux, nginx, MySQL, PHP
  • (Redis使用系列) Springboot 实现Redis 同数据源动态切换db 八
  • (二)【Jmeter】专栏实战项目靶场drupal部署
  • (附源码)计算机毕业设计SSM基于健身房管理系统
  • (力扣记录)235. 二叉搜索树的最近公共祖先
  • (十五)Flask覆写wsgi_app函数实现自定义中间件
  • (新)网络工程师考点串讲与真题详解
  • (转)linux 命令大全
  • .gitignore
  • .NET 2.0中新增的一些TryGet,TryParse等方法
  • .NET Compact Framework 3.5 支持 WCF 的子集
  • .net mvc actionresult 返回字符串_.NET架构师知识普及
  • .net反编译工具
  • .NET开源的一个小而快并且功能强大的 Windows 动态桌面软件 - DreamScene2
  • .NET开源项目介绍及资源推荐:数据持久层 (微软MVP写作)
  • .NET设计模式(8):适配器模式(Adapter Pattern)
  • .net中我喜欢的两种验证码
  • .stream().map与.stream().flatMap的使用
  • /usr/bin/env: node: No such file or directory
  • [⑧ADRV902x]: Digital Pre-Distortion (DPD)学习笔记
  • [APIO2012] 派遣 dispatching
  • [AUTOSAR][诊断管理][ECU][$37] 请求退出传输。终止数据传输的(上传/下载)
  • [hive]中的字段的数据类型有哪些