SringBoot集成WebSocket实现发送到指定用户案例

一、相关依赖


            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            org.springframework.boot
            spring-boot-starter-websocket
        

二、核心代码 

1)、WebSocketConfig 

/**
 * @program: test_demo
 * @description: 配置websocket
 * @author: HQ Zheng
 * @create: 2019-12-04 10:05
 */
@Configuration
//注解开启使用STOMP协议来传输基于代理(message broker)的消息,这时控制器支持使用@MessageMapping,就像使用@RequestMapping一样
@EnableWebSocketMessageBroker
//SpringBoot2.x将extends AbstractWebSocketMessageBrokerConfigurer改为 implements WebSocketMessageBrokerConfigurer
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {//注册STOMP协议的节点(endpoint),并映射指定的url
        //注册名为"endpointTest"的endpoint
        registry.addEndpoint("/endpointTest").addInterceptors(
                new HandshakeInterceptor() {
                    @Override
                    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Map map) throws Exception {
                        ServletServerHttpRequest req = (ServletServerHttpRequest) request;
                        //获取token认证
                        String token = req.getServletRequest().getParameter("token");
                        if (!token.equals("123")) {
                            return false;
                        }

                        return true;
                    }

                    @Override
                    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

                    }
                }
        ).setAllowedOrigins("*") //允许跨域
                .withSockJS();//指定使用SockJS协议

    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {//配置消息代理(Message Broker)
        //点对点式应配置/queue和/topic消息代理
        registry.enableSimpleBroker("/queue", "/topic");
        registry.setUserDestinationPrefix("/queue");

    }
}

2)、WebSocketController 

/**
 * @program: test_demo
 * @description: webSocket 控制器
 * @author: HQ Zheng
 * @create: 2019-12-04 10:16
 */
@Controller
@EnableScheduling  //定时任务支持
public class WebSocketController {

    //通过simpMessagingTemplate向浏览器发送消息
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    /**
     * 服务端推送消息到指定用户得客户端
     * 例如以下将会推送到
     * 因为设置了setUserDestinationPrefix("/userTest"),因此推送到/userTest/fanqi/info
     * 如果没有设置setUserDestinationPrefix(),则默认前端为user,将会推送到/user/fanqi/info
     * 客户端订阅/userTest/fanqi/info将会收到服务端推送得消息
     *
     * @return
     * @throws Exception
     */
    @Scheduled(initialDelay = 7000, fixedRate = 2000)
    public String serverTimeToUser() throws Exception {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpMessagingTemplate.convertAndSendToUser("test", "/info", df.format(new Date())+"哈哈哈");
        return "serverTimeToUser";
    }


}

三、html代码




    
    SpringBoot实现推送信息到指定用户WebSocket
    
    
    



四、测试

SringBoot集成WebSocket实现发送到指定用户案例_第1张图片

 

你可能感兴趣的:(WebSocket,SpringBoot)