首页 > 其他分享 >springboot集成websocket

springboot集成websocket

时间:2023-05-21 17:45:33浏览次数:40  
标签:集成 username websocket springboot webSocketSet map3 String put 在线

导入依赖

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-websocket</artifactId>
4 </dependency>

编写配置类

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }

}

3.核心配置类(WebSocket.java[类名可自定义])

//实例一个session,这个session是websocket的session
private Session session;

//存放当前用户名
private String userName;

//存放需要接受消息的用户名
private String toUserName;

//存放在线的用户数量
private static Integer userNumber = 0;

//存放websocket的集合(本次demo不会用到,聊天室的demo会用到)
private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

@OnOpen

//前端请求时一个websocket时
@OnOpen
public void onOpen(Session session,@PathParam("username") String username) throws IOException {
    this.session = session;
    //将当前对象放入webSocketSet
    webSocketSet.add(this);
    //增加在线人数
    userNumber++;
    //保存当前用户名
    this.userName = username;
    //获得所有的用户
    Set<String> userLists = new TreeSet<>();
    for (WebSocket webSocket : webSocketSet) {
        userLists.add(webSocket.userName);
    }

    //将所有信息包装好传到客户端(给所有用户)
    Map<String, Object> map1 = new HashMap();
    //  把所有用户列表
    map1.put("onlineUsers", userLists);
    //messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
    map1.put("messageType", 1);
    //  返回用户名
    map1.put("username", username);
    //  返回在线人数
    map1.put("number", this.userNumber);
    //发送给所有用户谁上线了,并让他们更新自己的用户菜单
    sendMessageAll(JSON.toJSONString(map1),this.userName);
    log.info("【websocket消息】有新的连接, 总数:{}", this.userNumber);

    // 更新在线人数(给所有人)
    Map<String, Object> map2 = new HashMap();
    //messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
    map2.put("messageType", 3);
    //把所有用户放入map2
    map2.put("onlineUsers", userLists);
    //返回在线人数
    map2.put("number", this.userNumber);
    // 消息发送指定人(所有的在线用户信息)
    sendMessageAll(JSON.toJSONString(map2),this.userName);
}

@OnClose

//前端关闭时一个websocket时
@OnClose
public void onClose() throws IOException {
    //从集合中移除当前对象
    webSocketSet.remove(this);
    //在线用户数减少
    userNumber--;
    Map<String, Object> map1 = new HashMap();
    //messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
    map1.put("messageType", 2);
    //所有在线用户
    map1.put("onlineUsers", this.webSocketSet);
    //下线用户的用户名
    map1.put("username", this.userName);
    //返回在线人数
    map1.put("number", userNumber);
    //发送信息,所有人,通知谁下线了
    sendMessageAll(JSON.toJSONString(map1),this.userName);
    log.info("【websocket消息】连接断开, 总数:{}", webSocketSet.size());
}

 


@OnMessage

//前端向后端发送消息
@OnMessage
public void onMessage(String message) throws IOException {
    log.info("【websocket消息】收到客户端发来的消息:{}", message);
    //将前端传来的数据进行转型
    com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(message);
    //获取所有数据
    String textMessage = jsonObject.getString("message");
    String username = jsonObject.getString("username");
    String type = jsonObject.getString("type");
    String tousername = jsonObject.getString("tousername");
    //群发
    if(type.equals("群发")){
        Map<String, Object> map3 = new HashMap();
        map3.put("messageType", 4);
        //所有在线用户
        map3.put("onlineUsers", this.webSocketSet);
        //发送消息的用户名
        map3.put("username", username);
        //返回在线人数
        map3.put("number", userNumber);
        //发送的消息
        map3.put("textMessage", textMessage);
        //发送信息,所有人,通知谁下线了
        sendMessageAll(JSON.toJSONString(map3),this.userName);
    }
    //私发
    else{
        //发送给对应的私聊用户
        Map<String, Object> map3 = new HashMap();
        map3.put("messageType", 4);
        //所有在线用户
        map3.put("onlineUsers", this.webSocketSet);
        //发送消息的用户名
        map3.put("username", username);
        //返回在线人数
        map3.put("number", userNumber);
        //发送的消息
        map3.put("textMessage", textMessage);
        //发送信息,所有人,通知谁下线了
        sendMessageTo(JSON.toJSONString(map3),tousername);

        //发送给自己
        Map<String, Object> map4 = new HashMap();
        map4.put("messageType", 4);
        //所有在线用户
        map4.put("onlineUsers", this.webSocketSet);
        //发送消息的用户名
        map4.put("username", username);
        //返回在线人数
        map4.put("number", userNumber);
        //发送的消息
        map4.put("textMessage", textMessage);
        //发送信息,所有人,通知谁下线了
        sendMessageTo(JSON.toJSONString(map3),username);
    }
}

 


SendMessageAll(自定义发送消息,发送消息給所有人)

/**
 *  消息发送所有人
 */
public void sendMessageAll(String message, String FromUserName) throws IOException {
    for (WebSocket webSocket: webSocketSet) {
        //消息发送所有人(同步)getAsyncRemote
        webSocket.session.getBasicRemote().sendText(message);
    }
}

 


私信发送(指定发送人)

public void sendMessageTo(String message, String ToUserName) throws IOException {
    //遍历所有用户
    for (WebSocket webSocket : webSocketSet) {
        if (webSocket.userName.equals(ToUserName)) {
            //消息发送指定人
            webSocket.session.getBasicRemote().sendText(message);
            log.info("【发送消息】:", this.userName+"向"+ToUserName+"发送消息:"+message);
            break;
        }
    }
}

 

 

 

 

标签:集成,username,websocket,springboot,webSocketSet,map3,String,put,在线
From: https://www.cnblogs.com/qijiangforever/p/17418872.html

相关文章

  • springboot+mybatis逆向生成xxxmapper+xxxmapper.xml和xxx实体类
    1.新建springboot工程pom文件如下<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="ht......
  • SpringBoot利用自定义注解实现多数据源
    自定义多数据源SpringBoot利用自定义注解实现多数据源,前置知识:注解、Aop、SpringBoot整合Mybaits1、搭建工程创建一个SpringBoot工程,并引入依赖<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring......
  • java基于springboot+vue的土特产在线销售平台、特产在线销售商城,附源码+数据库+lw文档
    1、项目介绍考虑到实际生活中在藏区特产销售管理方面的需要以及对该系统认真的分析,将系统权限按管理员和用户这两类涉及用户划分。(1)管理员功能需求管理员登陆后,主要模块包括首页、个人中心、用户管理、特产信息管理、特产分类管理、特产分类管理、特产评分管理、系统管理、订单......
  • Redis笔记(四):Java集成和配置
    JedisJedis是Redis官方提供的Java客户端,用于在Java应用程序中连接、操作Redis,它提供了与Redis通信的API,简化了Java开发者与Redis的交互流程。JedisGithubReadme:https://github.com/redis/jedis#getting-startedSpringBoot在SpringBoot2.x之后,原来使用的jedis被替换成了lettc......
  • SpringBoot读取Yml配置文件工具类
    SpringBoot读取Yml配置文件工具类在某些特定的环境,需要在非SpringBean中读取Yml文件,可以使用以下方式读取:需要依赖<dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>24.1-jre</v......
  • springboot的xml和java对象转换
    packagecom.zygh.tscmp.pojo;importcom.fasterxml.jackson.annotation.JsonFormat;importcom.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;importcom.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;importcom.faster......
  • springboot整合redis
     前言Redis是一款key-value存储结构的内存级NoSQL数据库支持多种数据存储格式支持持久化支持集群Redis下载(Windows版)https://github.com/tporadowski/redis/releasesRedis安装与启动(Windows版)Windows解压安装或一键式安装服务端启动命令redis-server.exe......
  • Jenkins 自动部署 SpringBoot
    Jenkins是流行的CI/DI工具。什么是CI/DI呢?CI/CD的核心概念可以总结为三点:持续集成持续交付持续部署简单来说就是将不同代码的分支合并到主分支,并自动进行打包,编译,测试,部署到生产环境的交付流程。 在这里用阿里云主机演示Jenkins自动部署SpringBoot项目。可以到阿里云官......
  • 什么是springboot&什么是spring
    1.什么是springbootspringboot是一个基于spring的开发框架,旨在简化sping应用的初始配置和开发过程。Springboot集成了对大部分目前流行的开发框架,使得开发者能够快速搭建spring项目。Springboot的核心设计思想是“约定优于配置”,基于这一原则,springboot极大地简化了项目和框架地......
  • springboot基于vue的MOBA类游戏攻略分享平台、游戏资讯分享平台,附源码+数据库+lw文档+
    1、项目介绍任何系统都要遵循系统设计的基本流程,本系统也不例外,同样需要经过市场调研,需求分析,概要设计,详细设计,编码,测试这些步骤,基于java语言设计并实现了MOBA类游戏攻略分享平台。该系统基于B/S即所谓浏览器/服务器模式,应用java技术,选择MySQL作为后台数据库。系统主要包括系统首......