springboot实现webSocket服务端和客户端demo

2023-09-12 21:48:04

1:pom导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>2.2.7.RELEASE</version>
        </dependency>

2:myWebSocketClient自定义webSocket客户端

package com.example.poi.utils;

import org.springframework.stereotype.Component;
import javax.websocket.*;
import java.io.IOException;

/**
 * @Author xu
 * @create 2023/9/11 18
 */
@ClientEndpoint
@Component
public class MyWebSocketClient {

    public Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.out.println("WebSocket2连接已打开");
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("收到消息2:" + message);
    }

    @OnClose
    public void onClose() {
        System.out.println("客户端关闭2");
    }
    
    @OnError
    public void onError(Throwable throwable) {
        System.err.println("发生错误2:" + throwable.getMessage());
    }
    
    public void sendMessage(String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }
}

3:WebSocketServer自定义webSocket服务端

package com.example.poi.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author xu
 * @create 2023/7/21 19
 */

@ServerEndpoint("/websocket/{sid}")
@Component
@Slf4j
public class WebSocketServer {

    static Log log = LogFactory.get(WebSocketServer.class);

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

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

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


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

    /**
     * 连接建立成功调用的方法
     *
     * @param session
     * @param sid
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this); //加入set中
        addOnlineCount(); //在线数加1
        log.info("有新窗口开始监听:" + sid + ",当前在线人数为" + getOnlineCount());
        this.sid = sid;
        /*try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }*/
    }

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

    /**
     * 收到客户端消息后调用的方法
     * 客户端发送过来的消息
     *
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口" + sid + "的信息:" + message);
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            if (ObjectUtils.equals(item.sid, sid)) {
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("name", sid);
                    item.sendMessage(jsonObject.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

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

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

    /**
     * 获取存在的webSocket
     */
    public CopyOnWriteArraySet<WebSocketServer> getWebSocketServer() {
        return webSocketSet;
    }

    public String getSid(){
        return sid;
    }

    public  void close2(String ss){
        for (WebSocketServer webSocketServer : webSocketSet) {
            if (webSocketServer.sid.equals(ss)) {
                webSocketSet.remove(webSocketServer);
                log.info("删除了:"+ss);
            }
        }
        subOnlineCount(); //在线数减1
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }


    /**
     * 发送消息
     *
     * @param message
     * @param sid
     * @throws IOException
     */
    public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {
        log.info("推送消息到窗口" + sid + ",推送内容:" + message);
        for (WebSocketServer item : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的,为null则全部推送
                if (sid == null) {
                    item.sendMessage(message);
                } else if (item.sid.equals(sid)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

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

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

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


    /**
     * 必须要有这个bean才能生效使用webSocketServer
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

4:controller控制层

    @SneakyThrows
    @GetMapping("/testSql")
    public List<EntityDemo> testSql(String id) {
        /** WebSocket服务器的地址*/
        try {
            Random random = new Random();
            Integer i = random.nextInt(5) + 1;
            CopyOnWriteArraySet<WebSocketServer> webSocketServerSet = webSocketServer.getWebSocketServer();
            for (WebSocketServer socketServer : webSocketServerSet) {
                if (socketServer.getSid().equals(i.toString())) {
                    webSocketServer.close2(i.toString());
                    return null;
                }
            }
            URI uri = new URI("ws://127.0.0.1:9088/test/websocket/" + i);
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            container.connectToServer(myWebSocketClient, uri);
            myWebSocketClient.sendMessage("你好" + i);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        log.info("++++++");
        return null;
    }

5:注意事项:连接自动断开

  • webSocket连接之后,发现一个问题:就是每隔一段时间如果不传送数据的话,与前端的连接就会自动断开。采用心跳消息的方式,就可以解决这个问题。比如客服端每隔30秒自动发送ping消息给服务端,服务端返回pong

5-1:注意事项:对象无法自动注入

  • 使用了@ServerEndpoint注解的类中使用@Resource或@Autowired注入对象都会失败,并且报空指针异常,解决方法:如下
  • @ServerEndpoint注解的类,使用静态对象,并且对外暴露set方法,这样在对象初始化的时候,将其注入到WebSocketServer
@ServerEndpoint("/websocket/{sid}")
@Component
@Slf4j
public class WebSocketServer {

    private static EntityDemoServiceImpl entityDemoService;

    public static void setEntityDemoService(EntityDemoServiceImpl entityDemoService) {
        WebSocketServer.entityDemoService = entityDemoService;
    }
  • 在要注入到@ServerEndpoint注解的类中,使用@PostConstruct后置注入
@Service
public class EntityDemoServiceImpl extends ServiceImpl<EntityDemoMapper, EntityDemo> implements IEntityDemoService {
    @PostConstruct
    public void init() {
        WebSocketServer.setEntityDemoService(this);
    }
}

5-2:注意事项:Session无法被序列化

  • 分布式场景会存在这样一个问题,当一次请求负载到第一台服务器时,session在第一台服务器线程上,第二次请求,负载到第二台服务器上,此时通过userId查找当前用户的session时,是查找不到的。
    本来想着把session存入到redis中,就可以从redis获取用户的session,希望用这种方式来解决分布式场景下消息发送的问题。这种场景可以通过发送消息中间件的方式解决。具体这样解决:每次连接时,都将userId和对应的session存入到本机,发送消息时,直接发送给MQ-Broker,然后每台应用负载都去消费这个消息,拿到消息之后,判断在本机能根据userId是否能找到session,找到则推送到客户端
更多推荐

TCP详解之流量控制

TCP详解之流量控制发送方不能无脑的发数据给接收方,要考虑接收方处理能力。如果一直无脑的发数据给对方,但对方处理不过来,那么就会导致触发重发机制,从而导致网络流量的无端的浪费。为了解决这种现象发生,TCP提供一种机制可以让「发送方」根据「接收方」的实际接收能力控制发送的数据量,这就是所谓的流量控制。下面举个栗子,为了简

百度之星(夏日漫步)

夏日夜晚,小度看着庭院中长长的走廊,萌发出想要在上面散步的欲望,小度注意到月光透过树荫落在地砖上,并且由于树荫的遮蔽度不通,所以月光的亮度不同,为了直观地看到每个格子的亮度,小度用了一些自然数来表示它们的亮度。亮度越高则数字越大,亮度相同的数字相同。走廊是只有一行地砖的直走廊。上面一共有n个格子,每个格子都被小度给予了

如何给API签名

前言有时候为了保护API,需要用到API签名,使用API签名的好处:让API只能被特定的人访问防止别人抓包拿到请求参数,通过篡改参数发起新的请求客户端过程给API调用者分配一个app_id和app_secret,app_secret调用者和服务端各保存一份,不对外泄露,app_id需要在调用API时作为参数传递。除了a

分布式电源接入对配电网影响分析(Matlab代码实现)

💥💥💞💞欢迎来到本博客❤️❤️💥💥🏆博主优势:🌞🌞🌞博客内容尽量做到思维缜密,逻辑清晰,为了方便读者。⛳️座右铭:行百里者,半于九十。📋📋📋本文目录如下:🎁🎁🎁目录💥1概述📚2运行结果🎉3参考文献🌈4Matlab代码、数据、文章💥1概述分布式电源的接入将配电系统从传统的无源放射

Qt 中多媒体模块的使用

Qt模块中类的介绍Qt中摄像头的使用是在QtMultimedia模块中。QtMultimedia是一个重要模块,它提供了一组丰富的QML类型和C++类来处理多媒体内容。它还提供了访问相机和无线电功能所需的API。随附的Qt音频引擎提供了用于3D位置音频播放和内容管理的类型。Qt中的多媒体支持由模块提供。Qt多媒体模块提

录屏没有声音怎么办,3个方法教你解决

随着科技的不断发展,人们越来越依赖电子设备进行工作和学习。在这个过程中,录屏已经成为了一种必要的技能。无论是手机还是电脑,我们都可以通过录屏来记录重要的信息。但是,有时候我们在录屏时会发现声音无法正常录制,这是一个非常令人头疼的问题。本文将详细介绍录屏没有声音怎么办,帮助大家解决录屏没有声音的问题。手机录屏没有声音方法

C++进阶(二)

目录1、Vector2D默认构造、重载2、char深度理解3、深度理解简单的类操作1、Vector2D默认构造、重载#include<iostream>#include<cmath>classVector2D{private:doublex;//X坐标doubley;//Y坐标public://默认构造函数,将向量初始

这个发表在 Nature Genetics的水稻全基因组关联数据库 RHRD,很赞!!!

历经半个世纪的发展,杂交水稻育种取得了巨大的成就,培育出了大量的高产、优质、适应环境变化的品系。本数据库是一个综合性的杂交水稻数据库(http://ricehybridresource.cemps.ac.cn/#/),涵盖了从1976年至2017年间发布的486个商业杂交水稻品种信息、基因组变异、表型与全基因组关联数据

【Flink实战】Flink自定义的Source 数据源案例-并行度调整结合WebUI

🚀作者:“大数据小禅”🚀文章简介:【Flink实战】玩转Flink里面核心的SourceOperator实战🚀欢迎小伙伴们点赞👍、收藏⭐、留言💬目录导航什么是Flink的并行度Flink自定义的Source数据源案例-并行度调整结合WebUI什么是Flink的并行度Flink的并行度是指在Flink应用程序中

自然语言处理实战项目18-NLP模型训练中的Logits与损失函数的计算应用项目

大家好,我是微学AI,今天给大家介绍一下,自然语言处理实战项目18-NLP模型训练中的Logits与损失函数的计算应用项目,在NLP模型训练中,Logits常用于计算损失函数并进行优化。损失函数的计算是用来衡量模型预测结果与真实标签之间的差异,从而指导模型参数的更新。Logits是模型在分类任务中的输出,在经过Soft

【程序员接口干货】热门免费的api接口大全

企业基本信息API:通过公司名称/公司ID/注册号或社会统一信用代码获取企业基本信息,企业基本信息包括公司名称或ID、类型、成立日期、经营状态、注册资本、法人、工商注册号、统一社会信用代码、组织机构代码、纳税人识别号等字段信息。企业联系方式查询API:通过公司名称、公司ID、注册号或社统一信用代码获取企业联系方式信息,

热文推荐