SpringBoot-WebSocket在线聊天和离线聊天

实现一对一聊天

testCompile group: 'junit', name: 'junit', version: '4.12'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-websocket', version: '2.5.5'
compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.18.22'

implementation group: 'com.baomidou', name: 'mybatis-plus-boot-starter', version: '3.4.3.4'
implementation group: 'com.h2database', name: 'h2', version: '1.4.200'
server:
  port: 8080
spring:
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:test
    username: root
    password: 1234
    schema: classpath:db/schema-h2.sql
    data: classpath:db/data-h2.sql
  h2:
    console:
      enabled: true
      path: /h2-database

# Mybatis-plus配置
mybatis-plus:
  #配置Mapper映射文件
  mapper-locations: classpath*:/mapper/*Mapper.xml
  # 配置MyBatis数据返回类型别名(默认别名是类名)
  type-aliases-package: com.aa.pojo
  configuration:
    # 自动驼峰命名
    map-underscore-to-camel-case: false
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
/**
db/schema-h2.sql
 */
DROP TABLE IF EXISTS offline_msg;
CREATE TABLE offline_msg(
  id int NOT NULL AUTO_INCREMENT COMMENT '主键id',
  fromId int NULL DEFAULT NULL COMMENT '发送者id',
  toId int NULL DEFAULT NULL COMMENT '接收者id',
  msg varchar(255) NULL DEFAULT NULL COMMENT '消息'
);
@SpringBootApplication
public class App {
   
    public static void main(String[] args) {
   
        ConfigurableApplicationContext run = SpringApplication.run(App.class,args);
        WebSocket.setApplicationContext(run);
    }
}
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("offline_msg")
public class OfflineMsg implements Serializable {
   

    private static final long serialVersionUID = 1L;

    @TableId(type = IdType.AUTO)
    private String id;
    private Integer fromId;
    private Integer toId;
    private String msg;
}
@Mapper
public interface OfflineMsgMapper extends BaseMapper<OfflineMsg> {
   
}
@ServerEndpoint("/ws/{uid}")
@Component
@Data
public class WebSocket{
   
    private static ApplicationContext applicationContext;


    public static void setApplicationContext(ApplicationContext applicationContext) {
   
        WebSocket.applicationContext = applicationContext;
    }
    public static OfflineMsgMapper offlineMsgMapper(){
   
        return applicationContext.getBean(OfflineMsgMapper.class);
    }

    private static int onlineCount = 0;
    public static Logger log= LoggerFactory.getLogger(WebSocket.class);
    private static ConcurrentHashMap<Integer,Session> mapUS = new ConcurrentHashMap<>();//根据用户找session
    private static ConcurrentHashMap<Session,Integer> mapSU = new ConcurrentHashMap<>();//根据session找用户
    public Session session;



    @OnOpen
    public void onOpen(Session session1, @PathParam("uid") Integer uid){
   
        session=session1;
        mapUS.put(uid,session);//添加唯一标识的用户ID为key,session为值
        mapSU.put(session,uid);//添加session为key,唯一标识的用户ID为值
        addOnlineCount();           //在线数加1

        System.out.println("有新连接用户:"+uid+"加入!当前在线人数为:" + getOnlineCount());
        List<OfflineMsg> msgs = offlineMsgMapper().selectList(new QueryWrapper<OfflineMsg>().eq("toId", uid));
        if (msgs.size()!=0){
   
            offlineMsgMapper().deleteBatchIds(msgs);
            log.info("用户"+uid+"上线,推送离线消息");
            for (OfflineMsg msg : msgs) {
   
                session.getAsyncRemote().sendText(msg.getFromId()+":"+msg.getMsg());
            }
        }

    }
    @OnClose
    public void onClose(Session session) {
   
        Integer uid = mapSU.get(session);
        mapUS.remove(uid);
        mapSU.remove(session);
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount())<
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值