springboot2.0.2 websocket 广播消息和一对一通信配置初始化

import com.cmd.exchange.common.constants.WebSocketTopicKey;
import org.springframework.context.annotation.Bean;
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;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

/**
 * 参考https://spring.io/guides/gs/messaging-stomp-websocket/
 * 注意: websocket的url和rest接口的url一定要区分,否则websocket握手的请求会跑到rest接口里,导致建立链接失败。
 * 错误的信息: 服务器返回状态码200
 * Created by linmingren on 2017/8/30.
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

//    @Bean
//    public ServerEndpointExporter serverEndpointExporter() {
//        return new ServerEndpointExporter();
//    }
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        //一对一订阅发送
        config.setUserDestinationPrefix(WebSocketTopicKey.P2PPUSHBASEPATH);
        //有3个主题可以发布信息, 客户端注册到这些主题下面的具体的内容
        config.enableSimpleBroker(
                WebSocketTopicKey.PRODUCERPATH1,
                WebSocketTopicKey.PRODUCERPATH2,
                WebSocketTopicKey.PRODUCERPATH3,
                WebSocketTopicKey.P2PPUSHBASEPATH,//一对一通信需要注册订阅
                WebSocketTopicKey.PRODUCERPATH4);
        //这个是处理客户端主动发上来的请求
        config.setApplicationDestinationPrefixes(WebSocketTopicKey.WEBSOCKETPATHPERFIX);

    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //如果客户端不支持websocket, 则使用sockjs
        //必须配置setAllowedOrigins, 否则浏览器连接websocket会提示403

        registry.addEndpoint(WebSocketTopicKey.WEBSOCKETPATH).setAllowedOrigins("*").withSockJS();
        //必须配置握手处理器,否则stomp客户端无法连接
        registry.addEndpoint(WebSocketTopicKey.WEBSOCKETPATH)
                .setHandshakeHandler(new DefaultHandshakeHandler(new TomcatRequestUpgradeStrategy()))
                .setAllowedOrigins("*");
    }


}

  2、服务端发送消息给客服端,一对一通讯订阅拼接方式如:“/user/唯一标识的id/msg”

template.convertAndSendToUser(websocketMonitor.getUser()+"", WebSocketTopicKey.P2PPUSHPATH, roomDataResponse);

  3、服务端广播消息

//订阅,广播发送内容 
template.convertAndSend("/xx/xx/xx", xxx);

  

posted @ 2019-10-16 14:46  _ylsn  阅读(561)  评论(0编辑  收藏  举报