首页 > 其他分享 >初次使用 WebSocket -springboot 集成

初次使用 WebSocket -springboot 集成

时间:2023-02-01 10:12:02浏览次数:67  
标签:集成 WebSocket springboot void clientId item message public String

参考自:SpringBoot 集成websocket_清泉影月的博客-CSDN博客WebSocket中利用service层交互数据库_戒烟的李白的博客-CSDN博客_websocketservice

核心依赖

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

<!--用于把字符串转json 可不配置-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>

配置类

import com.deloitte.WebsocketServer.WebSocketServer;
import com.deloitte.mapper.system.SysUsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter endpointExporter() {
        return new ServerEndpointExporter();
    }

//用来配置交互数据库 直接使用@Autowired 空指针 @Autowired private void SysUsersMapper(SysUsersMapper sysUsersMapper){ WebSocketServer.sysUsersMapper=sysUsersMapper; } }

服务

@Component
@Service
@ServerEndpoint("/websocket/{clientId}")
public class WebSocketServer {



    //静态变量,用来记录当前在线连接数
    private static int onlineCount = 0;

    //用来存放每个客户端对应的的连接信息
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

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

    //连接的 clientId
    private String clientId = "";

    /**
     * 前端连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("clientId") String clientId) {
        this.session = session;
        this.clientId = clientId;
        webSocketSet.add(this);
        addOnlineCount();
        try {
            String msg = "clientId:" + clientId + "连接成功,当前在线客户端数:" + getOnlineCount();
            sendMessage(msg);
            System.err.println(msg);

        } catch (IOException e) {
            System.err.println("client:{},连接故障,原因:{}"+ clientId+ e.getMessage());
        }
    }

    /**
     * 前端连接关闭调用的方法
     * 可以在里面写一些关闭连接需要处理的逻辑
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        System.err.println("释放连接,clientId:{};当前连接数:{}"+ clientId+getOnlineCount());
    }


    public static SysUsersMapper sysUsersMapper; //换成自己的

    /**
     * 该方法用于接受客户端发送的消息
     * 当前逻辑是:相同 clientId 的连接可以接受消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {

       // System.err.println("收到来自clientId:{} 的消息:{}"+clientId+ message);

        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        map = gson.fromJson(message, map.getClass());
        System.err.println(map.get("frozen"));
        String s=map.get("frozen")+"";
        sysUsersMapper.savelog(s,s,s,s, s, s);


        for (WebSocketServer item : webSocketSet) {
            try {
                if (item.clientId.equals(clientId)) {   //广播发送的话就去掉if
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                System.err.println("client:{} 发送消息故障,原因:{}"+ item.clientId+ e.getMessage());
            }
        }
    }

    /**
     * 用于记录发生的错误
     */
    @OnError
    public void one rror(Session session, Throwable e) {
        System.err.println("出现故障:{}"+e.getMessage());
    }

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

    /**
     * 定向 clientId 发送消息
     */
    public void sendInfo(String clientId, String message) throws IOException {
        System.err.println("推送消息到clientId:{},msg:{}"+clientId+message);
        for (WebSocketServer item : webSocketSet) {
            if (item.clientId.equals(clientId)) {
                item.sendMessage(message);
            }
        }
    }

    /**
     * 群发消息,广播形式
     */
    public void sendInfoAll(String message) throws IOException {
        for (WebSocketServer item : webSocketSet) {
            item.sendMessage(message);
        }
    }

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

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

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

    public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
        return webSocketSet;
    }
}

附测试地址:websocket在线测试 (websocket-test.com)

标签:集成,WebSocket,springboot,void,clientId,item,message,public,String
From: https://www.cnblogs.com/cjb1/p/17081648.html

相关文章

  • SpringBoot2.0版本与老版本区别
    SpringBoot2.0版本新特性 以Java8为基准SpringBoot2.0要求Java版本必须8以上,Java6和7不再支持。内嵌容器包结构调整为了支持reactive使用场景,内嵌的容器包结构......
  • SpringBoot实现热部署
    在项目开发的过程中,会频繁修改类的代码,导致需要重新编译、启动,影响开发效率。SpringBoot提供了spring-boot-devtools组件,使代码改动后,无须手动重启SpringBoot应用即可重......
  • SpringBoot设置日志级别
    输出到控制台logging:#日志记录到文件中file:#指定文件名name:server.loglogback:rollingpolicy:#指定文件大小max-file-size......
  • vue+springboot集成钉钉扫码登录
    具体接入方式可参考官方介绍:https://open.dingtalk.com/document/orgapp-server/tutorial-obtaining-user-personal-information本文只演示vue+springboot如何实现钉钉扫......
  • SpringBoot 开发抖音开放平台获取用户的粉丝统计和短视频数据
    大家好,我是小悟​抖音开放平台刚面世不久,资料比较少。即使对于一个开发人员来说,接入第三方接口都大同小异,不会太难,但我还是想把这些记录下来,特别是遇到的坑,会列在下面,一起参......
  • 抖音小程序集成支付宝支付
    ​大家好,我是小悟申请开通支付申请开通支付功能时,需要在小程序开发者的后台提交申请,如下图所示,并且提供以下资料:商户名称(公司名称)法人姓名渠道支付的业务场景(暂时只支持......
  • SpringBoot项目前端使用vue下载后端resources下的文件(导出模板)
     放到resources/xls/import-template.xls这个路径可以自己修改代码同步修改即可 @GetMapping(value="/downloadXls")@ApiOperation(value="下载导入模板"......
  • SpringBoot 整合 JDBC 实例
     0、数据库表CREATEDATABASEspringboot;USEspringboot;CREATETABLE`user`(`id`int(11)NOTNULLAUTO_INCREMENTCOMMENT'主键',`name`varchar(50)D......
  • SpringBoot项目动态定时任务之 ScheduledTaskRegistrar(解决方案一)
    前言​ 在做SpringBoot项目的过程中,有时客户会提出按照指定时间执行一次业务的需求。​ 如果客户需要改动业务的执行时间,即动态地调整定时任务的执行时间,那么可以采用S......
  • Springboot 中 Elasticsearch 使用
    项目中所使用代码已开源:​​https://gitee.com/szwei/elasticsearch​​项目中使用依赖版本:依赖版本spring-boot2.3.1.RELEASEelasticsearch7.9.3-windows-x86_64kibana7......