189 8069 5689

SpringBoot中添加Websocket支持的方法

背景

SpringBoot是由Pivotal团队在2013年开始研发、2014年4月发布第一个版本的全新开源的轻量级框架。它基于Spring4.0设计,不仅继承了Spring框架原有的优秀特性,而且还通过简化配置来进一步简化了Spring应用的整个搭建和开发过程。另外SpringBoot通过集成大量的框架使得依赖包的版本冲突,以及引用的不稳定性等问题得到了很好的解决。

创新互联公司长期为上1000+客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为蟠龙企业提供专业的网站设计、成都做网站蟠龙网站改版等技术服务。拥有十余年丰富建站经验和众多成功案例,为您定制开发。

WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。

WebSocket通信协议于2011年被IETF定为标准RFC 6455,并被RFC7936所补充规范。

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

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



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

完整pom.xml




    
    4.0.0
    com.qfx
    qfxSpringbootWebsocketServerDemo
    1.0
    war
    qfxSpringbootWebsocketServerDemo
    Springboot和Websock整合的示例

    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.1.RELEASE
         
    

    
    
        UTF-8
        UTF-8
        1.8
        
        -Dfile.encoding=UTF-8
    

    
        
        
        
            org.springframework.boot
            spring-boot-starter-web
            
                
                    org.springframework.boot
                    spring-boot-starter-logging
                
            
        

        
        
            org.springframework.boot
            spring-boot-starter-log4j2
        

        
        
            org.springframework.boot
            spring-boot-starter-tomcat
            provided
        

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

    
        
        qfxSpringbootWebsocketServerDemo
        
            
                
                    org.springframework.boot
                    spring-boot-maven-plugin
                    
                        
                        
                            org.springframework
                            springloaded
                            1.2.8.RELEASE
                        
                    
                
            
        
    

2. 添加Websocket配置类

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

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

/**
 * 
描述:如果使用外部Tomcat部署的话,则不需要此配置
*   */ @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;

/**
 * 
描述:WebSocket服务端
*  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 webSocketSet = new CopyOnWriteArraySet();    //与某个客户端的连接会话,需要通过它来给客户端发送数据    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,只要指定为不一样的即可




    
    My WebSocket test page



    Welcome
               

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

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

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

/**
 * 
描述:测试发送消息
*   */ @RestController @RequestMapping("message") public class SendCtl {    /**     *
功能:发送信息给正在连接websocket的所有用户
    *     * @param msg 消息内容     * @return     */    @RequestMapping("sendAllInfo")    public String sendAllInfo(String msg) {        WebSocketSer.sendInfo(msg, null);        return "success";    }    /**     *
功能:发送信息给正在连接websocket的指定所有用户
    *     * @param msg 消息内容     * @param cid 用户id     * @return     */    @RequestMapping("sendInfo")    public String sendInfo(String msg, String cid) {        WebSocketSer.sendInfo(msg, cid);        return "success";    } }

6. 完整目录结构

SpringBoot中添加Websocket支持的方法

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)发送信息

SpringBoot中添加Websocket支持的方法

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

SpringBoot中添加Websocket支持的方法

后台输出

SpringBoot中添加Websocket支持的方法

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

SpringBoot中添加Websocket支持的方法

后台输出

SpringBoot中添加Websocket支持的方法

两个Html页面都接收到信息

SpringBoot中添加Websocket支持的方法
SpringBoot中添加Websocket支持的方法

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

发送指定信息给cid_0002

SpringBoot中添加Websocket支持的方法

后台输出

SpringBoot中添加Websocket支持的方法

webSocket2.html(cid_0002)接收到信息

SpringBoot中添加Websocket支持的方法

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

SpringBoot中添加Websocket支持的方法


分享文章:SpringBoot中添加Websocket支持的方法
文章URL:http://cdxtjz.cn/article/pgideh.html

其他资讯