消息推送(1)

参考一:

 http 流的方式

https://blog.csdn.net/u011350550/article/details/83340657      

参考二

spring boot +websocket 服务器主动推送消息

https://blog.csdn.net/qq_35638499/article/details/80928356

WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端

这里我将使用springboot2.0 集成的websocket 实现简单的服务器推送消息

1.gradle添加依赖

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

2.配置spring已启动webSocket和stomp进行消息传递

//springBoot2.0版本后使用 实现WebSocketMessageBrokerConfigurer接口;
//2.0以下版本继承AbstractWebSocketMessageBrokerConfigurer 类;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //注册一个Stomp 协议的endpoint指定URL为myWebSocket,并用.withSockJS()指定 SockJS协议。.setAllowedOrigins("*")设置跨域
        registry.addEndpoint("/myWebSocket").setAllowedOrigins("*").withSockJS();
    }
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        //配置消息代理(message broker)
        //将消息传回给以‘/topic’开头的客户端
        config.enableSimpleBroker("/topic");
    }
}

3.发送消息

@Component
public class WebSocketComponent {
    @Autowired
    private SimpMessagingTemplate simpMessageSendingOperations;//消息发送模板
 
    @Scheduled(fixedRate = 1000 * 30)//每隔30秒向客户端发送一次数据
    public void sendMessage() {
        simpMessageSendingOperations.convertAndSend("/topic/ip", "我是从服务器来的消息!");//将消息推送给‘、topic/ip’的客户端
    }
}

4.HTML接收消息

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>webSocketTest</title>
        <script src="https://code.jquery.com/jquery.min.js"></script>
        <script src="https://cdn.bootcss.com/sockjs-client/1.1.0/sockjs.min.js"></script>
        <script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
    </head>
    <body>
    <div>
        <div class="form-group">
            <label for="connect">WebSocket connection:</label>
            <button id="connect" type="submit">Connect</button>
        </div>
    </div>
    <script>
        var stompClient = null;
        function connect() {
    //        var socket = new SockJS("/myWebSocket");运行后端服务,在浏览器输入localhost:8080/index.html
            var socket = new SockJS("http://localhost:8080/myWebSocket");//如果前后端分离项目需要拼接具体地址,前后端分离index.html可放在
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function (frame) {
                console.log(frame);
                stompClient.subscribe('/topic/ip', function (body) {
                    console.log(body);
            alert(body.body) }); }); } $(function () { $(
"#connect").click(function (e) { connect(); e.preventDefault(); }); }); </script> </body> </html>

5.springBoot启动类

@SpringBootApplication
@EnableScheduling
public class DsApplication {
    public static void main(String[] args) {
        SpringApplication.run(DsApplication.class, args);
    }
}

6.前后端分离项目跨域配置

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);
    }
}

7.如果项目有spring security需要在webSecurityConfig中配置websocket的静态资源访问

@SuppressWarnings("SpringJavaAutowiringInspection")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Autowired
    AuthenticationTokenFilter authenticationTokenFilter;
 
    @Bean
    public Http401AuthenticationEntryPoint unauthorizedEntryPoint() {
        return new Http401AuthenticationEntryPoint("");
    }
 
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/myWebSocket/**");//允许访问websocket定义的stomp协议资源
    }
 
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .cors().and()
                .csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint()).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                // 允许对于网站静态资源的无授权访问,登录接口无授权访问
                .antMatchers(HttpMethod.POST, "/**").permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();
 
    }
}

8.运行结果 


点击Connet,按F12 console 输出如下结果 


 

原文地址:https://www.cnblogs.com/lshan/p/10319465.html