java中使用sockjs、stomp完成websocket通信

这篇具有很好参考价值的文章主要介绍了java中使用sockjs、stomp完成websocket通信。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

主要配置

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;



/**
 * @author
 * WebSocket配置类
 */
@Slf4j
@Configuration
@AllArgsConstructor
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    private final WebSocketInterceptor webSocketInterceptor;
    private final WebSocketHandshakeInterceptor webSocketHandshakeInterceptor;
    public static final String USER_DESTINATION_PREFIX = "/salaryother/";
    public static final String CALL_DEVICE_NOTIFY_PATH = USER_DESTINATION_PREFIX + "CALL_DEVICE_NOTIFY/";

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        log.info("WebSocket服务器注册");
        registry.addEndpoint("/ws")
                .addInterceptors(webSocketHandshakeInterceptor)
                .setHandshakeHandler(new WebSocketHandshakeHandler())
                .setAllowedOrigins("*")
                .withSockJS();

        registry.addEndpoint("/wsapp")
                .addInterceptors(webSocketHandshakeInterceptor)
                .setHandshakeHandler(new WebSocketHandshakeHandler())
                .setAllowedOrigins("*");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        log.info("WebSocket服务器启动");
        //心跳检测
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(10);
        threadPoolTaskScheduler.setThreadNamePrefix("wss-heartbeat-thread-");
        threadPoolTaskScheduler.initialize();
        ///信息接收头
        registry.enableSimpleBroker("/topic", USER_DESTINATION_PREFIX)
                .setHeartbeatValue(new long[]{10000, 10000}).setTaskScheduler(threadPoolTaskScheduler);
        //接收前缀
        registry.setApplicationDestinationPrefixes("/topic");
        //请求前缀
        registry.setUserDestinationPrefix("/user");
    }

    /**
     * 配置发送与接收的消息参数,可以指定消息字节大小,缓存大小,发送超时时间
     *
     * @param registration
     */
    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
        /*
         * 1. setMessageSizeLimit 设置消息缓存的字节数大小 字节
         * 2. setSendBufferSizeLimit 设置websocket会话时,缓存的大小 字节
         * 3. setSendTimeLimit 设置消息发送会话超时时间,毫秒
         */
        registration.setMessageSizeLimit(10240)
                .setSendBufferSizeLimit(10240)
                .setSendTimeLimit(10000);
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {

        /*
         * 配置消息线程池
         * 1. corePoolSize 配置核心线程池,当线程数小于此配置时,不管线程中有无空闲的线程,都会产生新线程处理任务
         * 2. maxPoolSize 配置线程池最大数,当线程池数等于此配置时,不会产生新线程
         * 3. keepAliveSeconds 线程池维护线程所允许的空闲时间,单位秒
         */
        registration.taskExecutor().corePoolSize(10)
                .maxPoolSize(60)
                .keepAliveSeconds(60);
        registration.interceptors(webSocketInterceptor);
    }

    //  这个是为了解决和调度任务的冲突重写的bean
    @Primary
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(10);
        taskScheduler.initialize();
        return taskScheduler;
    }


}

握手拦截(这套方案好像前端无法补充Header,就不在这里做权限校验)这里采用的方法是直接问号拼接token,前端 new SockJS(这里带问号),sockjs使用的是http所以没毛病,本文使用的是OAuth2权限校验

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.joolun.cloud.common.security.entity.BaseUser;
import com.joolun.cloud.common.security.util.SecurityUtils;
import io.micrometer.core.lang.NonNullApi;
import io.micrometer.core.lang.Nullable;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@Component
@NonNullApi
@AllArgsConstructor
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
    private WebSocketManager webSocketManager;
    private RemoteTokenServices tokenService;
//SecurityUtils.getUser()代码
//    SecurityContextHolder.getContext().getAuthentication().getPrincipal()
//     principal instanceof BaseUser ? (BaseUser)principal : null;

    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) {
        String token = getToken(serverHttpRequest);
        if (StrUtil.isBlank(token)) return false;
        // 验证令牌信息
        try {
            OAuth2Authentication auth2Authentication = tokenService.loadAuthentication(token);
            if (ObjectUtil.isNull(auth2Authentication)) return false;
            SecurityContextHolder.getContext().setAuthentication(auth2Authentication);
        } catch (Exception e) {
            log.error("token验证失败");
            return false;
        }
        BaseUser user = SecurityUtils.getUser();
        String userId = user.getId();
        map.put("WebSocket-user", new WebSocketUserAuthentication(userId, user.getUsername(), token));
        webSocketManager.addUser(userId, token);
        log.info("userId:" + userId + "用户名:" + user.getUsername() + ":开始建立连接");
        return true;

    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, @Nullable Exception e) {
        BaseUser user = SecurityUtils.getUser();
        log.info("userId:" + user.getId() + "用户名:" + user.getUsername() + ":建立连接完成");
    }


    private String getToken(ServerHttpRequest serverHttpRequest) {
        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) serverHttpRequest;
        HttpServletRequest httpServletRequest = servletRequest.getServletRequest();
        String token = httpServletRequest.getParameter("Authorization");
        return StrUtil.isBlank(token) ? "" : token;
    }

之后可以设置握手之后的身份注入(配置了这个可以在单对单订阅时直接使用)

import io.micrometer.core.lang.NonNullApi;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import java.security.Principal;
import java.util.Map;

@NonNullApi
public class WebSocketHandshakeHandler extends DefaultHandshakeHandler {
    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        return (Principal) attributes.get("WebSocket-user");
    }


}
import lombok.Data;

import java.security.Principal;

@Data
public class WebSocketUserAuthentication implements Principal {

    private String token;
    private String userId;
    private String userName;

    public WebSocketUserAuthentication(String userId, String userName,String token ) {
        this.token = token;
        this.userId = userId;
        this.userName = userName;
    }

    public WebSocketUserAuthentication() {
    }

    @Override
    public String getName() {
        return token;
    }

}

储存用户数据

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
public class WebSocketManager {

    Cache<String, String> webSocketUser;

    @PostConstruct
    public void init() {
        webSocketUser = Caffeine.newBuilder().initialCapacity(16).expireAfterWrite(60, TimeUnit.MINUTES).build();
    }

    public boolean isOnline(String userId) {
        return StringUtils.isNotBlank(webSocketUser.getIfPresent(userId));
    }

    public void addUser(String userId, String token) {
        webSocketUser.put(userId, token);
    }

    public String getTokenById(String userId) {
        return webSocketUser.getIfPresent(userId);
    }

    public void deleteUser(String userId) {
        webSocketUser.invalidate(userId);
    }
}

之后就是通道拦截,如果不使用握手拦截可以在这里鉴权,这里就可以拿到握手后发送的Header,前端就在headers里面添加

this.stompClient.connect(
        headers,
        () => {
        .....
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.joolun.cloud.common.security.entity.BaseUser;
import io.micrometer.core.lang.NonNullApi;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.stereotype.Component;

import java.util.Optional;


@Slf4j
@NonNullApi
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
@AllArgsConstructor
public class WebSocketInterceptor implements ChannelInterceptor {

    private WebSocketManager webSocketManager;
    private RemoteTokenServices tokenService;


    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
        if (ObjectUtil.isNull(accessor)) throw new MessagingException("获取数据失败");
        StompCommand stompCommand = accessor.getCommand();
        // 判断是否是连接或者断开请求
        if (StompCommand.CONNECT != stompCommand && StompCommand.DISCONNECT != stompCommand) return message;
        //拿取用户信息
        Optional<WebSocketUserAuthentication> user = getUser(accessor);
        if (!user.isPresent()) throw new MessagingException("获取用户失败");
        WebSocketUserAuthentication baseUser = user.get();
        String userId = baseUser.getUserId();
        // 下线请求
        if (StompCommand.DISCONNECT == stompCommand) {
            String userName = baseUser.getUserName();
            webSocketManager.deleteUser(userId);
            log.info("userId:" + userId + "用户名:" + userName + ":下线了");
        }
        return message;
    }


    /**
     * 在消息发送后立刻调用,boolean值参数表示该调用的返回值
     */
    @Override
    public void postSend(Message<?> message, MessageChannel messageChannel, boolean sent) {
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
        // 忽略心跳消息等非STOMP消息
        StompCommand command = accessor.getCommand();
        if (command == null) return;
        switch (command) {
            case CONNECT:
                log.info("上线了");
                break;
            case CONNECTED:
                log.info("已连接");
                break;
            case SUBSCRIBE:
                log.info("订阅:" + accessor.getDestination());
                break;
            case UNSUBSCRIBE:
                log.info("取消订阅:" + accessor.getDestination());
                break;
            case DISCONNECT:
                log.info("下线了");
                break;
            default:
                log.info("不匹配以上情况");
                break;
        }
    }

    private boolean isUserOAuth2Authentication(StompHeaderAccessor accessor) {
        String token = getToken(accessor);
        if (StrUtil.isBlank(token)) return false;
        try {
            // 验证令牌信息
            OAuth2Authentication auth2Authentication = tokenService.loadAuthentication(token);
            if (ObjectUtil.isNull(auth2Authentication)) return false;
            SecurityContextHolder.getContext().setAuthentication(auth2Authentication);
        } catch (Exception e) {
            log.error("token验证失败");
            return false;
        }
        return true;
    }

    private Optional<WebSocketUserAuthentication> getUser(StompHeaderAccessor accessor) {
        return accessor.getUser() instanceof WebSocketUserAuthentication ?
                Optional.of((WebSocketUserAuthentication) accessor.getUser()) :
                getSystemUserToWebSocketUserAuthentication(accessor)
                ;


    }

    private Optional<WebSocketUserAuthentication> getSystemUserToWebSocketUserAuthentication(StompHeaderAccessor accessor) {
        Authentication authentication = getAuthentication();
        if (ObjectUtil.isNull(authentication)) {
            if (isUserOAuth2Authentication(accessor)) {
                authentication = getAuthentication();
            } else {
                return Optional.empty();
            }
        }
        Object principal = authentication.getPrincipal();
        if (ObjectUtil.isNull(principal)) return Optional.empty();
        BaseUser user = principal instanceof BaseUser ? (BaseUser) principal : null;
        if (ObjectUtil.isNotNull(user)) {
            WebSocketUserAuthentication webSocketUserAuthentication = new WebSocketUserAuthentication(user.getId(), user.getUsername(), getToken(accessor));
            accessor.setUser(webSocketUserAuthentication);
            return Optional.of(webSocketUserAuthentication);
        }
        return Optional.empty();

    }

    private String getToken(StompHeaderAccessor accessor) {
        String tokens = accessor.getFirstNativeHeader("Authorization");
        if (StrUtil.isBlank(tokens)) return "";
        return tokens.split(" ")[1];
    }

    private Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

}

配置完成之后就是发送消息这里就不举详细的例子了就拿SimpMessageSendingOperations来说

//引入
import org.springframework.messaging.simp.SimpMessageSendingOperations;

private final SimpMessageSendingOperations simpMessageSendingOperations;
private final WebSocketManager webSocketManager;

如果配置了握手拦截器返回了Principal 个人消息

订阅地址:/user/salaryother/activistIncoming
发送地址:/salaryother/activistIncoming
发送消息:
 simpMessageSendingOperations.convertAndSendToUser
                    (webSocketManager.getTokenById(用户id), 发送地址, 消息);

如果没配置那就得多加几个前缀具体参考请点击:
Spring Springboot实现websocket通讯-2 这个详细

微信小程序连接websocket文章来源地址https://www.toymoban.com/news/detail-683705.html

到了这里,关于java中使用sockjs、stomp完成websocket通信的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • WebSocket的那些事(5-Spring中STOMP连接外部消息代理)

    上节我们在 WebSocket的那些事(4-Spring中的STOMP支持详解) 中详细说明了通过 Spring内置消息代理 结合 STOMP 子协议进行Websocket通信,以及相关注解的使用及原理。 但是Spring内置消息代理会有一些限制,比如只支持STOMP协议的一部分命令,像 acks 、 receipts 命令都是不支持的,还有

    2024年02月09日
    浏览(28)
  • WebSocket的那些事(5-Spring STOMP支持之连接外部消息代理)

    上节我们在 WebSocket的那些事(4-Spring中的STOMP支持详解) 中详细说明了通过 Spring内置消息代理 结合 STOMP 子协议进行Websocket通信,以及相关注解的使用及原理。 但是Spring内置消息代理会有一些限制,比如只支持STOMP协议的一部分命令,像 acks 、 receipts 命令都是不支持的,还有

    2024年02月09日
    浏览(30)
  • Spring Boot 3 + Vue 3 整合 WebSocket (STOMP协议) 实现广播和点对点实时消息

    🚀 作者主页: 有来技术 🔥 开源项目: youlai-mall 🍃 vue3-element-admin 🍃 youlai-boot 🌺 仓库主页: Gitee 💫 Github 💫 GitCode 💖 欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请纠正! WebSocket是一种在Web浏览器与Web服务器之间建立双向通信的协议,而Spring Boot提供了便捷的WebSocket支持

    2024年02月02日
    浏览(40)
  • WebSocket(三) -- 使用websocket+stomp实现群聊功能

    SpringBoot+websocket的实现其实不难,你可以使用原生的实现,也就是websocket本身的OnOpen、OnClosed等等这样的注解来实现,以及对WebSocketHandler的实现,类似于netty的那种使用方式,而且原生的还提供了对websocket的监听,服务端能更好的控制及统计(即上文实现的方式)。 但是,真

    2023年04月08日
    浏览(29)
  • flutter开发实战-长链接WebSocket使用stomp协议stomp_dart_client

    flutter开发实战-长链接WebSocket使用stomp协议stomp_dart_client 在app中经常会使用长连接进行消息通信,这里记录一下基于websocket使用stomp协议的使用。 1.1 stomp介绍 stomp,Streaming Text Orientated Message Protocol,是流文本定向消息协议,是一种为MOM(Message Oriented Middleware,面向消息的中间件

    2024年02月13日
    浏览(37)
  • 使用Spring WebSocket实现实时通信功能

    🌷🍁 博主猫头虎(🐅🐾)带您 Go to New World✨🍁 🦄 博客首页 ——🐅🐾猫头虎的博客🎐 🐳 《面试题大全专栏》 🦕 文章图文并茂🦖生动形象🐅简单易学!欢迎大家来踩踩~🌺 🌊 《IDEA开发秘籍专栏》 🐾 学会IDEA常用操作,工作效率翻倍~💐 🌊 《100天精通Golang(基础

    2024年02月09日
    浏览(28)
  • 使用java完成WebSocket自动主动断开连接功能

    一个页面实时刷新的功能,页面上的数据状态可能会随着操作实时改变,所以每个用户在使用的时候都希望能看到数据的最新状态。 我想到了两种解决方法:1.轮循,2.WebSocket 我们这里采用的是WebSocket来解决问题 WebSocket在建立连接后,如果不是人为操作的话,他不会主动地进

    2024年02月07日
    浏览(40)
  • Springboot 整合 WebSocket ,使用STOMP协议+Redis 解决负载场景问题

    ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSeial.setObjectMapper(om); template.setValueSerializer(jacksonSeial); template.setKeySerializer(stringRedisSerializer); template.setHashKeySerializer(stringRedisSerializer); template

    2024年04月14日
    浏览(46)
  • Springboot 整合 WebSocket ,使用STOMP协议 ,前后端整合实战 (一)(1)

    server: port: 9908 3.WebSocketConfig.java import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springfra

    2024年04月25日
    浏览(35)
  • Android程序中使用websocket通信(java-websocket)

    使用场景: 需要和硬件保持实时通信 为什么用websocket: 在以前的消息推送机制中,用的都是http轮询(polling),做一个定时器定时向服务器发送请求,这种方式是非常消耗资源的,因为它本质还是http请求,而且显得非常笨拙。而WebSocket 在浏览器和服务器完成一个握手的动作

    2024年01月23日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包