首页 > 其他分享 >springboot+websocket简单使用

springboot+websocket简单使用

时间:2023-06-20 17:37:15浏览次数:34  
标签:webSocketMap websocket springboot userId springframework session 简单 import publi

一、引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo1</name>
    <description>demo1</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

二、config配置

package com.example.demo.config;

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

/**
 * WebSocket配置
 *
 * @author caozz
 * @since 2023/6/20 16:30
 */
@Configuration
public class WebSocketConfig {

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

}

三、WebSocketServer

package com.example.demo.config;

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.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket server服务
 *
 * @author caozz
 * @since 2023/6/20 16:40
 */
@ServerEndpoint("/{userId}")
@Component
public class WebSocketServer {

    private static int onlineCount = 0;     // 在线人数
    public static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();   // session管理map
    private Session session;    // 会话session
    private String userId="";   // 当前用户

    /**
     * 初始化连接
     *
     * @param session 会话session
     * @param userId 当前用户id
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        System.out.println("客户端:"+userId+"连接成功");
        this.session = session;
        this.userId=userId;

        // 保存各用户的会话session
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        }else{
            webSocketMap.put(userId, this);
            addOnlineCount();
        }

        try {
            sendMessage(userId + " connect success!");
        } catch (IOException e) {

        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        System.out.println("连接已经关闭了,");
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            subOnlineCount();
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:"+message);
        //返回消息给客户端
        try {
            // session 就是客户端和服务器自连接起来建立的会话
            // 直到关闭连接直接这个会话一直是连接的,所以我们在这个过程中可以用它给客户端推送消息
            session.getBasicRemote().sendText("client,I have received your message");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 异常处理
     * @param session
     * @param error
     */
    @OnError
    public void one rror(Session session, Throwable error) {
        System.out.println("System Error!msg:" + error);
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送自定义消息
     *
     * @param message 消息体
     * */
    public void sendInfo(String message) throws IOException {

        List<String> keys = new ArrayList<>(webSocketMap.keySet());

            for (String key : keys) {
                webSocketMap.get(key).sendMessage(message);
            }

    }

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

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

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

四、推送消息

这里不一定要访问接口,也可以服务端监听数据变化,或者数据入库时触发

package com.example.demo.controller;

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

import static com.example.demo.config.WebSocketServer.webSocketMap;

/**
 * @Author: caozhouzhou
 * @Date: 2023/6/20 16:53
 **/
@RestController
public class HelloWorld {

    @GetMapping("/hello")
    public String hello() throws Exception {
        for (String userId:webSocketMap.keySet()) {
            webSocketMap.get(userId).sendMessage("我是服务端,现在广播推送一条消息。。。");
        }
        return "SUCCESS";
    }
}

五、postman测试

  • 创建websocket连接

  • 填写信息并连接

  • 通过api触发服务端广播消息

欢迎大家留言,以便于后面的人更快解决问题!另外亦欢迎大家可以关注我的微信公众号,方便利用零碎时间互相交流。共勉!

标签:webSocketMap,websocket,springboot,userId,springframework,session,简单,import,publi
From: https://www.cnblogs.com/caozz/p/websocket.html

相关文章

  • springboot简易配置
    server:port:8089servlet:encoding:charset:UTF-8tomcat:uri-encoding:UTF-8spring:datasource:type:com.zaxxer.hikari.HikariDataSourcejdbc-url:jdbc:mysql://localhost:3306/mydb_base?serverTimezone=UTC&useUnicode=t......
  • 简单旋转
    @OverridepublicvoidonDraw(Canvascanvas){//Thissavesoffthematrixthatthecanvasappliestodraws,soitcanberestoredlater.canvas.save();//nowwechangethematrix//Weneedtorotatearoundthecenterofourtext//......
  • 简单的添加item
    很多人不是很理解如何添加数据这里是最简单的一种publicclassDemonstrateextendsListActivity{privatestaticfinalintADD_ITEM=0;privatestaticfinalintREMOVE_ITEM=1;privatestaticfinalintEXIT_ITEM=2;privateArrayAdapter<String>......
  • 一个简单的基于SSM框架的公告展示系统
    测试环境:本章系统使用SSM+layui实现各个模块,Web服务器使用Tomcat8.5.75,数据库采用的是MySQL8.0,集成开发环境为IntelliJIDEA2022.1,导入项目后需要先更新maven,然后在项目结构中添加tomcat依赖,并在mysql数据库中创建7张与系统相关的数据表。先看成品。公告标题可以点击,点击进去后是......
  • SpringBoot整合Cache缓存深入理解
    我们在上一篇的基础上继续学习。SpringBoot整合cache缓存入门一、@Caching注解@Caching注解用于在方法或者类上,同时指定多个Cache相关的注解。属性名描述cacheable用于指定@Cacheable注解put用于指定@CachePut注解evict用于指定@CacheEvict注解示例代码如下:importcom.example.mys......
  • SpringBoot02
    Springboot021.Springboot注册三大组件Servlet、Filter、Listener三大组件和我们之前学习的web阶段中Servlet、Filter、Listener一样servlet是一种运行服务器端的java应用程序,具有独立于平台和协议的特性,并且可以动态的生成web页面,它工作在客户端请求与服务器响应的中间层......
  • fileinput 简单操作
    importfileinputwithfileinput.input('a.txt')asf:#,backup=".bak",inplace=1backupinplace同时有参数才会备份print("*****访问一个文件'a.txt'****")forlineinf:print(line.strip())#print(line.strip(),......
  • 2、【java数据安全】base64与报文摘要MD(md5、sha、mac)简单介绍及应用场景、示例
    (文章目录)本文简单的介绍了Base64、消息摘要和其使用示例,并且使用示例以三种不同实现方式及测试本文介绍三种实现方式,即JDK、apachecommons.codec和bouncycastle三种。一、maven依赖<dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <......
  • Docker配置SpringBoot+ShardingJDBC+MybatisPlus项目实现分库分表与读写分离
    Docker配置SpringBoot+ShardingJDBC+MybatisPlus项目实现分库分表与读写分离 分类于 实战例子本文ShardingJDBC相关知识主要参考自ShardingJDBC官方文档,更多的用法建议到官网文档查看。前言传统的业务系统都是将数据集中存储至单一数据节点的解决方案,如今随着互联网数据......
  • 简单计算器(Java_图形用户界面设计)
    题目编写一个应用程序,包括三个文本框和四个按钮,分别是“加”、“减”、“乘”、“除”,单击相应的按钮,将两个文本框的数字做运算,在第三个文本框中显示结果。布局Codepackageunit_9;importjavax.swing.*;importjava.awt.*;importjava.awt.event.ActionEvent;importjava.awt......