Spring Boot 的websocket 配置

 1、websocket 配置

package com.iamgpj.websocket.config;

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.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @Description: webSocket 配置文件
 * @author: GPJ
 * @Date: 13:02 2018/4/10
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    /**
     * 注册端点,发布或者订阅消息的时候需要连接此端点
     * addEndpoint websocket的端点,客户端需要注册这个端点进行链接
     * setAllowedOrigins 非必须,*表示允许其他域进行连接,跨域
     * withSockJS 允许客户端利用sockjs进行浏览器兼容性处理
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/endpoints-websocket")
                .setAllowedOrigins("*")
                .withSockJS();
    }

    /**
     * 配置消息代理
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 设置服务器广播消息的基础路径
        registry.enableSimpleBroker("/topic", "/chat");
        // 设置客户端订阅消息的基础路径
        registry.setApplicationDestinationPrefixes("/app");
    }
}

2、前段连接监听

function connect() {
    var socket = new SockJS("/endpoints-websocket");
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function(frame) {
        setConnect(true);
        console.log("Connected: " + frame);
        stompClient.subscribe("/topic/game_rank", function (result) {
            console.log(result);
            showContent(JSON.parse(result.body));
        });
    });
}

猜你喜欢

转载自my.oschina.net/iamgpj/blog/1796887