spring-boot项目整合socket同时启用stomp模式-阿里云开发者社区

开发者社区> Java技术进阶> 正文
登录阅读全文

spring-boot项目整合socket同时启用stomp模式

简介: 直接使用WebSocket(或SockJS)就很类似于使用TCP套接字来编写Web应用。因为没有高层级的线路协议(wire protocol),因此就需要我们定义应用之间所发送消息的语义,还需要确保连接的两端都能遵循这些语义。

1.在项目pom文件中配置

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

2.创建user

public class User implements Principal {

    private final String name;

    public User(String name) {
        this.name = name;
    }

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

}

3.创建ChannelInterceptor

@Component
public class ChannelInterceptor extends ChannelInterceptorAdapter {


    /**
     * 获取包含在stomp中的用户信息
     */
    @SuppressWarnings("rawtypes")
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            Object raw = message.getHeaders().get(SimpMessageHeaderAccessor.NATIVE_HEADERS);
            if (raw instanceof Map) {
                Object name = ((Map) raw).get("name");
                if (name instanceof LinkedList) {
                    // 设置当前访问器的认证用户
                    accessor.setUser(new User(((LinkedList) name).get(0).toString()));
                }
            }
        }
        return message;
    }

}

4.创建WebSocketConfig


@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/market");
        registry.setApplicationDestinationPrefixes("/req");
        registry.setPreservePublishOrder(true);
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor());
    }

    /**
     *
     * @Title: createUserInterceptor
     * @Description: 将客户端渠道拦截器加入spring ioc容器
     * @return
     */
    @Bean
    public ChannelInterceptor createUserInterceptor() {
        return new ChannelInterceptor();
    }


}

5.使用stomp
在所需要操作业务对象中导入一下代码

@Autowired
 public SimpMessagingTemplate simpMessagingTemplate;
    @PostConstruct
    public void init() {
        simpMessagingTemplate.setMessageConverter(new SimpleMessageConverter());
    }

需要将数据推送到前台的代码中添加

 simpMessagingTemplate.convertAndSend("/market/demo", "hello word!");

6.前端代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>WebSocket</title>
</head>
<body onload="disconnect()">
<div>
    <div>
        <button id="connect" onclick="connect();">连接</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
    </div>
</div>
<script src="https://d1fxtkz8shb9d2.cloudfront.net/sockjs-0.3.4.min.js"></script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="./protobuf.js"></script>


<script type="text/javascript">
    let stompClient = null;

    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        $('#response1').html('');
    
    }

    function connect() {
        let socket = new SockJS('http://127.0.0.1:8080/ws');
        stompClient = Stomp.over(socket);
        stompClient.connect({
            name: 'TEST' // 携带客户端信息
        }, function(frame) {
            setConnected(true);
            var depth =stompClient.subscribe('/market/demo', function(respnose){
                $('#response1').html("stomp:"+respnose.body);
            });
        });
    }
    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("断开连接");

    }
</script>
</body>
</html>

7.如有疑问请在文章评论处评论

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
Java技术进阶
使用钉钉扫一扫加入圈子
+ 订阅

Java技术进阶成长,课程资料,案例解析,实战经验全都有!

官网链接