前言

http协议是无状态协议,每次请求都不知道前面发生了什么,而且只可以由浏览器端请求服务器端,而不能由服务器去主动通知浏览器端,是单向的,在很多场景就不适合,比如实时的推送,消息通知或者股票等信息的推送;在没有 websocket 之前,要解决这种问题,只能依靠 ajax轮询 或者 长轮询,这两种方式极大的消耗资源;而websocket,只需要借助http协议进行握手,然后保持着一个websocket连接,直到客户端主动断开;相对另外的两种方式,websocket只进行一次连接,当有数据的时候再推送给浏览器,减少带宽的浪费和cpu的使用。 WebSocket是html5新增加的一种通信协议,目前流行的浏览器都支持这个协议,例如Chrome,Safari,Firefox,Opera,IE等等,对该协议支持最早的应该是chrome,从chrome12就已经开始支持,随着协议草案的不断变化,各个浏览器对协议的实现也在不停的更新。该协议还是草案,没有成为标准,不过成为标准应该只是时间问题了,从WebSocket草案的提出到现在已经有十几个版本了,目前对该协议支持最完善的浏览器应该是chrome,毕竟WebSocket协议草案也是Google发布的,下面我们教程我们使用springboot 集成 websocket 实现消息的一对一以及全部通知功能。

本文使用spring boot 2.1.1+ jdk1.8 + idea。

一:引入依赖

如何创建springboot项目本文不再赘述,首先在创建好的项目pom.xml中引入如下依赖:

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

org.springframework.boot spring-boot-starter-thymeleaf

二:创建websocket配置类

ServerEndpointExporter 会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。要注意,如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。

package com.sailing.websocket.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.server.standard.ServerEndpointExporter;/** * @author baibing * @project: springboot-socket * @package: com.sailing.websocket.config * @Description: socket配置类,往 spring 容器中注入ServerEndpointExporter实例 * @date 2018/12/20 09:46 */@Configurationpublic class WebSocketConfig {    @Bean    public ServerEndpointExporter serverEndpointExporter(){        return new ServerEndpointExporter();    }}

三:编写websocket服务端代码

package com.sailing.websocket.common;import org.springframework.stereotype.Component;import javax.websocket.*;import javax.websocket.server.PathParam;import javax.websocket.server.ServerEndpoint;import java.io.IOException;import java.util.HashMap;import java.util.Map;import java.util.concurrent.atomic.AtomicInteger;/** * @author baibing * @project: springboot-socket * @package: com.sailing.websocket.common * @Description: WebSocket服务端代码,包含接收消息,推送消息等接口 * @date 2018/12/200948 */@Component@ServerEndpoint(value = "/socket/{name}")public class WebSocketServer {    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。    private static AtomicInteger online = new AtomicInteger();    //concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketServer对象。    private static Map sessionPools = new HashMap<>();    /**     * 发送消息方法     * @param session 客户端与socket建立的会话     * @param message 消息     * @throws IOException     */    public void sendMessage(Session session, String message) throws IOException{        if(session != null){            session.getBasicRemote().sendText(message);        }    }    /**     * 连接建立成功调用     * @param session 客户端与socket建立的会话     * @param userName 客户端的userName     */    @OnOpen    public void onOpen(Session session, @PathParam(value = "name") String userName){        sessionPools.put(userName, session);        addOnlineCount();        System.out.println(userName + "加入webSocket!当前人数为" + online);        try {            sendMessage(session, "欢迎" + userName + "加入连接!");        } catch (IOException e) {            e.printStackTrace();        }    }    /**     * 关闭连接时调用     * @param userName 关闭连接的客户端的姓名     */    @OnClose    public void onClose(@PathParam(value = "name") String userName){        sessionPools.remove(userName);        subOnlineCount();        System.out.println(userName + "断开webSocket连接!当前人数为" + online);    }    /**     * 收到客户端消息时触发(群发)     * @param message     * @throws IOException     */    @OnMessage    public void onMessage(String message) throws IOException{        for (Session session: sessionPools.values()) {            try {                sendMessage(session, message);            } catch(Exception e){                e.printStackTrace();                continue;            }        }    }    /**     * 发生错误时候     * @param session     * @param throwable     */    @OnError    public void onError(Session session, Throwable throwable){        System.out.println("发生错误");        throwable.printStackTrace();    }    /**     * 给指定用户发送消息     * @param userName 用户名     * @param message 消息     * @throws IOException     */    public void sendInfo(String userName, String message){        Session session = sessionPools.get(userName);        try {            sendMessage(session, message);        }catch (Exception e){            e.printStackTrace();        }    }    public static void addOnlineCount(){        online.incrementAndGet();    }    public static void subOnlineCount() {        online.decrementAndGet();    }}

四:增加测试页面路由配置类

如果为每一个页面写一个action太麻烦,spring boot 提供了页面路由的统一配置,在 spring boot 2.0 以前的版本中我们只需要继承 WebMvcConfigurerAdapter ,并重写它的 addViewControllers 方法即可,但是 2.0版本后 WebMvcConfigurerAdapter已经被废弃,使用 WebMvcConfigurer 接口代替(其实WebMvcConfigurerAdapter也是实现了WebMvcConfigurer),所以我们只需要实现它即可:

package com.sailing.websocket.config;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;/** * 在SpringBoot2.0及Spring 5.0 WebMvcConfigurerAdapter已被废弃,目前找到解决方案就有 * 1 直接实现WebMvcConfigurer (官方推荐) * 2 直接继承WebMvcConfigurationSupport * @ https://blog.csdn.net/lenkvin/article/details/79482205 */@Configurationpublic class WebMvcConfig implements WebMvcConfigurer {    /**     * 为各个页面提供路径映射     * @param registry     */    @Override    public void addViewControllers(ViewControllerRegistry registry) {        registry.addViewController("/client").setViewName("client");        registry.addViewController("/index").setViewName("index");    }}

五:创建测试页面

在 resources下面创建 templates 文件夹,编写两个测试页面 index.html 和 client.html 和上面配置类中的viewName相对应,两个页面内容一模一样,只是在连接websocket部分模拟的用户名不一样,一个叫 lucy 一个叫 lily :

    WebSocketWelcomeSend    Close
    WebSocketWelcomeSend    Close

六:测试webscoket controller

package com.sailing.websocket.controller;import com.sailing.websocket.common.WebSocketServer;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;import java.io.IOException;/** * @author baibing * @project: springboot-socket * @package: com.sailing.websocket.controller * @Description: websocket测试controller * @date 2018/12/20 10:11 */@RestControllerpublic class SocketController {    @Resource    private WebSocketServer webSocketServer;    /**     * 给指定用户推送消息     * @param userName 用户名     * @param message 消息     * @throws IOException     */    @RequestMapping(value = "/socket", method = RequestMethod.GET)    public void testSocket1(@RequestParam String userName, @RequestParam String message){        webSocketServer.sendInfo(userName, message);    }    /**     * 给所有用户推送消息     * @param message 消息     * @throws IOException     */    @RequestMapping(value = "/socket/all", method = RequestMethod.GET)    public void testSocket2(@RequestParam String message){        try {            webSocketServer.onMessage(message);        } catch (IOException e) {            e.printStackTrace();        }    }}

七:测试

访问 http://localhost:8080/index 和 http://localhost:8080/client 分别打开两个页面并连接到websocket,http://localhost:8080/socket?userName=lily&message=helloworld 给lily发送消息,http://localhost:8080/socket/all?message=LOL 给全部在线用户发送消息:

技术改变一切

socket接收的消息怎么更新到页面_spring boot 集成 websocket 实现消息主动相关推荐

  1. spring boot 集成 websocket 实现消息主动推送

    前言 http协议是无状态协议,每次请求都不知道前面发生了什么,而且只可以由浏览器端请求服务器端,而不能由服务器去主动通知浏览器端,是单向的,在很多场景就不适合,比如实时的推送,消息通知或者股票等信息 ...

  2. spring boot 集成socketIo 做消息推送

    spring boot 集成socketIo 做消息推送 项目需求 代码展示 客户端代码 服务端代码 项目需求 后台管理系统用户小铃铛,消息推送功能并展示有多少条消息或者小红点 代码展示 客户端代码 ...

  3. socket接收的消息怎么更新到页面_利用socketio实现简易即时消息服务

    背景简介 以前开发HTTP服务器更多使用的是python语言中的Flask框架来完成,但是在最近的业务中涉及到在web页面中实时获取消息更新,这个时候我能想到的解决方案 1.写一个循环ajax请求,不 ...

  4. 【RuoYi-Vue-Plus】扩展笔记 02 - 集成 WebSocket 发送消息到客户端(源码)

    文章目录 前言 关于需求实现的对比(轮询与 `WebSocket` ) 关于本篇文章 参考目录 代码实现参考 原理分析参考 集成流程 1.Maven 2.WebSocket 配置类 `WebSocke ...

  5. Springboot集成websocket实现消息推送和在线用户统计

    一.HTTP 说到websocket首先要说Http,Http大家都知道是一个网络通信协议,每当客户端浏览器需要访问后台时都会发一个请求,服务器给出响应后该连接就会关闭,请求只能有客户端发起,服务端是 ...

  6. SpringBoot 集成 WebSocket 实现消息群发推送

    一. 什么是 WebSocket WebSocket 是一种全新的协议.它将 TCP 的 Socket(套接字)应用在了web page上,从而使通信双方建立起一个保持在活动状态的连接通道,并且属于全 ...

  7. druid监控页面_Spring boot学习(四)Spring boot整合Druid

    前言 在上一篇博客中我们介绍了Spring boot配置Mybatis,但是并没有配置连接池,这在实际开发过程中肯定是不切实际的,多次的数据库连接会给程序和数据库都带来没必要的负担,这一篇博客我将介绍 ...

  8. glassfish启动后不能进入部署页面_Spring Boot 热部署

    实际开发中,修改某个页面数据或逻辑功能都需要重启应用.这无形中降低了开发效率,所以使用热部署是十分必要的. 什么是热部署? 应用启动后会把编译好的Class文件加载的虚拟机中,正常情况下在项目修改了源 ...

  9. thymeleaf 点击按钮跳转页面_spring boot使用thymeleaf跳转页面实例代码

    前言 在学习springboot 之后想结合着html做个小demo,无奈一直没掌握窍门,在多番的搜索和尝试下终于找到了配置的方法,使用thymeleaf做事前端页面模板,不能使用纯html. thy ...

最新文章

  1. python的深拷贝与浅拷贝
  2. 51Nod - 2142身份证号排序
  3. 佛缘——宝华山隆昌寺之行
  4. php一点按钮就下载功能源码,php实现强制文件下载方法的源码参考
  5. java水果超市mysql_Java基础 | 项目实战之水果超市
  6. 苹果企业账号炒作到多少钱_从炒作到行动:边缘计算的后续步骤
  7. java 高效加减乘除_java简单加减乘除
  8. 论文阅读:Natural Language Processing Advancements By Deep Learning: A Survey
  9. 《高性能mysql》之MySQL高级特性(第七章)
  10. java课程 数独 文库_数独java代码
  11. con 元器件符号_Protues 元器件符号
  12. Ubuntu中安装VirtualBox
  13. 从零开始学JSON(修订版)
  14. m低信噪比下GPS信号的捕获算法研究,使用matlab算法进行仿真
  15. 第一水上软件 Hypack v10.05b 海洋调查和水道测量 HYPACK 2011
  16. 利用人性弱电的互联网服务
  17. Iterator方法详解
  18. 照片建模神器 Recap Photo
  19. 淘宝商品详情接口(原数据app、h5端)
  20. x86汇编_指令集大全_笔记_6

热门文章

  1. PaddleOCR加载chinese_ocr_db_crnn_modile模型进行中英文混合预测(Http服务)实践
  2. Hadoop权威指南pdf
  3. 数据脱敏项目中遇见的问题
  4. 影响JavaScript应用可扩展性因素
  5. UIKIT网页基本结构学习
  6. php in_array 和 str_replace
  7. Nginx TCP代理
  8. 使用nginx进行负载均衡
  9. 文件签名魔塔50层android反编译破解
  10. AspNetDB.mdf数据库的建立和使用