spring boot整合websocket

1.引入maven依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <!-- 与websocket冲突 -->
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

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

2.配置类

@Configuration
public class WebsocketConfig {
    /**
     * 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3.websocket监听类

@Slf4j
@ServerEndpoint(value = "/cre-data-manager-factory/factory/socket")
@Component
public class FactorySocket {

    /** 记录当前在线连接数 */
    public static AtomicInteger onlineCount = new AtomicInteger(0);

    /** 存放已经连接的session */
    public static Map<String,Session> sessionMap = new ConcurrentHashMap();


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) throws IOException {

        // websocket鉴权
        if (StringUtils.isEmpty(session.getQueryString()) || !session.getQueryString().contains("8dd2d7e7b0b54637")){
            log.info("websocket鉴权失败");
            session.close();
            return;
        }
        log.info(JSON.toJSONString(session.getRequestParameterMap()));
        onlineCount.incrementAndGet(); // 在线数加1
        sessionMap.put(session.getId(),session);
        log.info("有新连接加入:{},当前连接数为:{}", session.getId(), onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        sessionMap.remove(session.getId());
        log.info("有一连接关闭:{},当前连接数为:{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message);
        this.sendMessage("成功收到消息: " + message, session);
    }

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

    /**
     * 服务端发送消息给客户端
     */
    public void sendMessage(String message, Session toSession) {
        try {

            log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getAsyncRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败:{}", e);
        }
    }
}

ws://localhost:8217/cre-data-manager-factory/factory/socket 根据这样的请求串就可以连接socket

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值