SpringBoot入门二十,添加Websocket支持

项目基本配置参考SpringBoot入门一,使用myEclipse新建一个SpringBoot项目,使用myEclipse新建一个SpringBoot项目即可。此示例springboot的版本已经升级到2.2.1.RELEASE,具体步骤如下:

1. pom.xml添加以下配置信息

<!-- 4. 引入websocket支持 -->
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

完整pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <!-- 项目基本信息 -->
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.qfx</groupId>
    <artifactId>qfxSpringbootWebsocketServerDemo</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>
    <name>qfxSpringbootWebsocketServerDemo</name>
    <description>Springboot和Websock整合的示例</description>

    <!-- 设置父类,整合第三方常用框架依赖信息(各种依赖信息),这里继承SpringBoot提供的父工程 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <!-- 设置公共参数 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <!-- Maven install 时,测试环境@Test中如果有中文输出是乱码,加上这句话试试 -->
        <argLine>-Dfile.encoding=UTF-8</argLine>
    </properties>

    <dependencies>
        <!-- 1.开启springboot核心包,整合SpringMVC Web组件 -->
        <!-- 实现原理:Maven依赖继承关系,相当于把第三方常用Maven依赖信息,在parent项目中已经封装好了 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions><!-- 去掉默认日志配置 -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- 2.引入log4j2支持 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

        <!-- 3.打war包时加入此项, 告诉spring-boot tomcat相关jar包用外部的,不要打进去 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- 4. 引入websocket支持 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
    </dependencies>

    <build>
        <!-- 指定war包名称,以此处为准,否则会带上版本号 -->
        <finalName>qfxSpringbootWebsocketServerDemo</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <dependencies>
                        <!-- spring热部署 -->
                        <dependency>
                            <groupId>org.springframework</groupId>
                            <artifactId>springloaded</artifactId>
                            <version>1.2.8.RELEASE</version>
                        </dependency>
                    </dependencies>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

2. 添加Websocket配置类

如果使用外部Tomcat部署的话,则不需要此配置,否则启动会报异常

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * <h5>描述:如果使用外部Tomcat部署的话,则不需要此配置</h5>
 *
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3. 添加Websocket服务类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.concurrent.CopyOnWriteArraySet;

/**
 * <h5>描述:WebSocket服务端</h5>
 *  WebSocket是类似客户端服务端的形式(采用ws协议),
 *  所以 WebSocketServer其实就相当于一个ws协议的 Controller,
 *  可以在里面实现 @OnOpen、@onClose、@onMessage等方法
 */
@ServerEndpoint("/websocket/{cid}")
@Component
public class WebSocketSer {
    private static final Logger LOG = LoggerFactory.getLogger(WebSocketSer.class);

    // 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    // concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketSer> webSocketSet = new CopyOnWriteArraySet<WebSocketSer>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    // 接收cid
    private String cid = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("cid") String cid) {
        this.session = session;
        webSocketSet.add(this);     // 加入set中
        addOnlineCount();           // 在线数加1
        LOG.info("客户端: " + cid + " 连接成功, 当前在线人数为:" + getOnlineCount());
        this.cid = cid;
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            LOG.error("发送消息异常:", e);
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  // 从set中删除
        subOnlineCount();           // 在线数减1
        LOG.info("有一个连接关闭,当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        LOG.info("收到来自客户端 " + cid + " 的信息: " + message);
        // 群发消息
        for (WebSocketSer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        LOG.error("发生错误");
        error.printStackTrace();
    }

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

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message, @PathParam("cid") String cid) {
        LOG.info("推送消息到客户端:" + cid + ",内容: " + message);
        for (WebSocketSer item : webSocketSet) {
            try {
                // 这里可以设定只推送给这个cid的,为null则全部推送
                if (cid == null) {
                    item.sendMessage(message);
                } else if (item.cid.equals(cid)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

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

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

    public static synchronized void subOnlineCount() {
        WebSocketSer.onlineCount--;
    }
}

4. 添加Websocket测试webSocket.html和webSocket2.html页面

webSocket.html 与 webSocket2.html 中的cid 分别是cid_0001 和 cid_0002,只要指定为不一样的即可

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>My WebSocket test page</title>
</head>

<body>
    Welcome<br/>
    <input id="text" type="text"/>
    <button onclick="send()">Send</button>
    <button onclick="closeWebSocket()">Close</button>
    <div id="message"></div>
</body>

<script type="text/javascript">
    var websocket = null;

    //判断当前浏览器是否支持WebSocket
    if (‘WebSocket‘ in window) {
        // 端口默认为当前tomcat的端口,根据自己实际情况改变即可,"cid_0001"就是后端接收的参数cid
        // webSocket.html 配置
        websocket = new WebSocket("ws://localhost:80/qfxSpringbootWebsocketServerDemo/websocket/cid_0001");
        // webSocket2.html 配置
        // websocket = new WebSocket("ws://localhost:80/qfxSpringbootWebsocketServerDemo/websocket/cid_0002");
    } else {
        alert(‘Not support websocket‘)
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function (event) {
        setMessageInnerHTML(event.data);
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("close");
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        if (undefined != innerHTML) {
            document.getElementById(‘message‘).innerHTML += innerHTML + ‘<br/>‘;
        }
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        var message = document.getElementById(‘text‘).value;
        websocket.send(message);
    }
</script>
</html>

5. 编写一个发送消息的Controller

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.qfx.demo.common.service.WebSocketSer;

/**
 * <h5>描述:测试发送消息</h5>
 *
 */
@RestController
@RequestMapping("message")
public class SendCtl {

    /**
     * <h5>功能:发送信息给正在连接websocket的所有用户</h5>
     *
     * @param msg 消息内容
     * @return
     */
    @RequestMapping("sendAllInfo")
    public String sendAllInfo(String msg) {
        WebSocketSer.sendInfo(msg, null);
        return "success";
    }

    /**
     * <h5>功能:发送信息给正在连接websocket的指定所有用户</h5>
     *
     * @param msg 消息内容
     * @param cid 用户id
     * @return
     */
    @RequestMapping("sendInfo")
    public String sendInfo(String msg, String cid) {
        WebSocketSer.sendInfo(msg, cid);
        return "success";
    }
}

6. 完整目录结构

7. 测试连接

7.1 Html页面连接websocket服务端,分别打开webSocket.html和webSocket2.html页面,webSocket.html发送一条信息

http://127.0.0.1/qfxSpringbootWebsocketServerDemo/webSocket.html
http://127.0.0.1/qfxSpringbootWebsocketServerDemo/webSocket2.html

webSocket.html发送信息,两个页面都能够接收到,因为WebSocketSer.java的onMessage方法里面会进行群发

webSocket.html(cid_0001)发送信息

webSocket2.html(cid_0002)不做操作,也接收到了cid_0001发送的信息

后台输出

7.2 通过Controller给所有在线用户发送一条信息

后台输出

两个Html页面都接收到信息


7.3 通过Controller给指定在线用户发送一条信息

发送指定信息给cid_0002

后台输出

webSocket2.html(cid_0002)接收到信息

webSocket.html(cid_0001)没有接收到信息,因为不是发给他的

8、源码

移步码云下载

原文地址:https://blog.51cto.com/1197822/2462407

时间: 2024-07-30 23:42:06

SpringBoot入门二十,添加Websocket支持的相关文章

SpringBoot入门二十二,使用Validation进行参数校验

项目基本配置参考文章SpringBoot入门一,使用myEclipse新建一个SpringBoot项目,使用myEclipse新建一个SpringBoot项目即可,此示例springboot升级为2.2.1版本. 1. pom.xml添加aop支持 如果已经引用了spring-boot-starter-web,就不要需要引用spring-boot-starter-validation了,本例就不再引用 <!-- 引入validation支持 --> <dependency> <

[WebGL入门]二十,绘制立体模型(圆环体)

注:文章译自http://wgld.org/,原作者杉本雅広(doxas),文章中如果有我的额外说明,我会加上[lufy:],另外,鄙人webgl研究还不够深入,一些专业词语,如果翻译有误,欢迎大家指正. 本次的demo的运行结果 立体的模型 这次稍微喘口气,开始绘制立体模型.这里说的[喘口气]是指本次的文章中没有出现任何新的技术知识点.只是利用到现在为止所介绍过的内容,来绘制一个立体的圆环体.到现在为止,只绘制了三角形和四边形,当然,在三维空间中绘制简单的多边形也没什么不对,但是缺点儿说服力.

SpringBoot入门二,添加JdbcTemplate数据源

项目基本配置参考上一篇文章SpringBoot入门一,使用myEclipse新建一个SpringBoot项目即可.现在来给项目添加一个JdbcTemplate数据源,添加方式非常简单,仅需两步即可,具体内容如下: 1. pom.xml添加以下配置信息 <!-- jdbcTemplate依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring

SpringBoot入门二十三,整合Redis

项目基本配置参考文章SpringBoot入门一,使用myEclipse新建一个SpringBoot项目,使用MyEclipse新建一个SpringBoot项目即可,此示例springboot升级为2.2.1版本. 1. pom.xml添加Redis支持 <!-- 5.引入redis依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-b

springboot 入门二- 读取配置信息一

在上篇入门中简单介绍下springboot启动使用了大量的默认配置,在实际开发过程中,经常需要启动多个服务,那端口如何手动修改呢? 此篇就是简单介绍相关的配置文件信息. Spring Boot允许外部化你的配置,这样你就可以在不同的环境中使用相同的应用程序代码.你可以使用属性文件.YAML文件.环境变量和命令行参数来外部化配置.属性的值获取可以通过注解@Value . spring Environment或注解@ConfigurationProperties 这些方式优先级如下: @TestPr

为libevent添加websocket支持(上)

在跨平台网络基础库中,libevent与asio近年来使用比较广泛.asio对boost的依赖太大,个人认为发展前途堪忧,尤其asio对http没有很好的支持也是缺点之一. libevent对http有天生支持,含有服务与客户两个部分,是做web服务的好特性. libevent随对http支持很优秀,但并不支持html5标准的websocket,这有些与时代脱轨.如果你熟悉websocket协议,像自己扩展libevent,很遗憾,libevent的http部分并不支持逻辑层扩展.所以我想,还是

[WebGL入门]二十四,补色着色

注:文章译自http://wgld.org/,原作者杉本雅広(doxas),文章中如果有我的额外说明,我会加上[lufy:],另外,鄙人webgl研究还不够深入,一些专业词语,如果翻译有误,欢迎大家指正. 本次的demo的运行结果 着色方法 上次介绍了反射光,反射光是实现光泽的不可缺少的概念,到此为止,基本的光照效果都已经封装完毕了. 光照的效果主要就是扩散光,环境光和反射光三种方法,灵活运用这三种光照,应该就能实现非常逼真的照明效果了. 前几篇一直在说光照,这次稍微换个视点,看一下着色,着色是

[WebGL入门]二十二,从环境光源发出的光

注:文章译自http://wgld.org/,原作者杉本雅広(doxas),文章中如果有我的额外说明,我会加上[lufy:],另外,鄙人webgl研究还不够深入,一些专业词语,如果翻译有误,欢迎大家指正. 本次的demo的运行结果 平行光源的弱点 上次挑战了一下从平行光源发出的光.平行光源的光的方向是固定的.而且,为了模拟这些,需要用到模型变换矩阵的逆矩阵,以及需要向模型数据中加入法线情报等等.平行光源的计算负担比较小,在一定程度上模拟了光照效果,在3D模拟世界中经常被用到.但是,平行光源也有弱

Android入门(二十二)解析JSON

原文链接:http://www.orlion.ga/687/ 解析JSON的方式有很多,主要有官方提供的 JSONObject,谷歌的开源库 GSON.另外,一些第三方的开源库如 Jackson.FastJSON等也非常不错. 假设JSON数据为: [{"id":"5","version":"5.5","name":"Angry Birds"}, {"id":&quo