springboot整合websocket

springboot整合websocket迷你号

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

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


WebSocket的优势

我们都知道HTPP协议是基于请求响应模式,并且无状态的。HTTP通信只能由客户端发起,HTTP 协议做不到服务器主动向客户端推送信息。
在这里插入图片描述
举例来说,我们想要查询当前的排队情况,只能是页面轮询向服务器发出请求,服务器返回查询结果。轮询的效率低,非常浪费资源(因为必须不停连接,或者 HTTP 连接始终打开)。因此WebSocket 就是在这样的背景下发明的。


例子说明

引入maven

  <!--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
  6. 因为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连接

前端页面直接使用ws协议建立连接,const socketUrl = “ws://localhost:9091/api/pushMessage/” + $(“#userId”).val();

<!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>

运行结果

服务器端向客户端发送消息
在这里插入图片描述

客户端向服务器端发送消息
在这里插入图片描述

在这里插入图片描述


本文总结

本文先简单阐述了下websocket的概念,分析了websocket的优势,以及其与传统的http请求的区别与联系。最后编写了一个例子来说明websocket的使用,帮助大家快速上手websocket。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/157733.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 数组和链表的区别,各有何优缺点

    数组和链表的区别,各有何优缺点链表与数组的区别(1)数组的元素个数是固定的,而组成链表的结点个数可按需要增减;(2)数组元素的存诸单元在数组定义时分配,链表结点的存储单元在程序执行时动态向系统申请;(3)数组中的元素顺序关系由元素在数组中的位置(即下标)确定,链表中的结点顺序关系由结点所包含的指针来体现。(4)对于不是固定长度的列表,用可能最大长度的数组来描述,会浪费许多内存空间。(5)对于元素的插人、删除操作非常频繁的列表处理场合,用数组表示是不适宜的。若用链表实现,会使程序结构清晰,处理的方法也较为简便。数组的优点随机

    2022年6月17日
    89
  • Hystrix:服务熔断

    Hystrix:服务熔断文章目录服务雪崩服务雪崩​多个微服务之间调用的时候,假设微服务A调用微服务B和微服务C,微服务B和微服务C又调用其他的微服务,这就是所谓的“扇出”,如果扇出的链路上某个微服务的调用响应时间过长,或者不可用,对微服务A的调用就会占用越来越多的系统资源,进而引起系统崩溃,所谓的“雪崩效应”。​对于高流量的应用来说,单一的后端依赖可能会导致所有服务器上的所有资源都在几十秒内饱和。比失败更糟糕的是,这些应用程序还可能导致服务之间的延迟增加,备份队列,线程和其他系统资源紧张,导致整个系统发生更多的级联故障,

    2022年10月21日
    2
  • VMware安装centos7(电动卷闸门安装方法及步骤)

    原文:https://www.jianshu.com/p/ce08cdbc4ddb?utm_source=tuicool&utm_medium=referral本篇文章主要介绍了VMware安装Centos7超详细过程(图文),具有一定的参考价值,感兴趣的小伙伴们可以参考一下1.软硬件准备软件:推荐使用VMwear,我用的是VMwear12镜像:CentOS7,如…

    2022年4月12日
    45
  • golang 永久激活破解方法

    golang 永久激活破解方法,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月14日
    1.7K
  • pycharm及python安装详细教程_python基础教程

    pycharm及python安装详细教程_python基础教程python下载安装图文教程-Pycharm下载安装图文教程Python及Pycharm安装图文教程,供大家参考,具体内容如下为了学习Python我今天对它进行了安装,并将Python及Pycharm安装方法进行了分享,希望可以帮助到大家注:建议大家在安装过程中不要将软件安装到系统盘中。1、Python安装1)首先需要进入Python官网下载安装包,进入后点击Downloads找到如下界面:可以根据自己的系统下载适合的安装包下载完成后直接…

    2022年8月27日
    4
  • Tomcat部署WAR包访问不带项目名的方式

    Tomcat部署WAR包访问不带项目名的方式1、将项目打成WAR包放在Tomcat的webapps目录下2、在Tomcat的安装目录的conf下找到server.xml的文件,如:D:\apache-tomcat-9.0.8\conf\server.xml3、在Host标签里边添加<Hostname=”localhost”appBase=”webapps”unpackWARs=”true”…

    2022年5月16日
    121

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号