• websocket消息推送实现


    一.服务层

    package com.reyo.websocket;
    
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.concurrent.ConcurrentLinkedQueue;
    
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.CloseStatus;
    import org.springframework.web.socket.TextMessage;
    import org.springframework.web.socket.WebSocketSession;
    import org.springframework.web.socket.config.annotation.EnableWebSocket;
    import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
    import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
    import org.springframework.web.socket.handler.TextWebSocketHandler;
    
    @Configuration
    @EnableWebSocket
    public class websocketListener implements WebSocketConfigurer, ServletContextListener{
        
        private ConcurrentLinkedQueue<WebSocketSession> sessions  = new ConcurrentLinkedQueue<WebSocketSession>();
        
        private WebSocketHandlerReYo handler;
        
        
        @Override
        public void contextDestroyed(ServletContextEvent arg0) {
            // TODO Auto-generated method stub
        }
    
        @Override
        public void contextInitialized(ServletContextEvent arg0) {
            // TODO Auto-generated method stub
            
        }
    
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            handler = new WebSocketHandlerReYo();
            registry.addHandler(handler, "/ws/notifymessage.ws");
            registry.addHandler(handler, "/ws/sockjs/notifymessage.ws").withSockJS();
            new Thread(handler).start();
        }
        
        class  WebSocketHandlerReYo extends TextWebSocketHandler implements Runnable{
            
            @Override
            public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
                sessions.remove(session);
            }
            
            @Override
            public void afterConnectionEstablished(WebSocketSession session) throws Exception {
                sessions.add(session);
            }
            
            @Override
            protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
                super.handleTextMessage(session, message);
            }
    
            @Override
            public void run() {
                System.out.println("等待推送....");
                try {
                    int i = 0;
                    for (;;) {
                        synchronized (this) {
                            try {
                                Thread.sleep(3000);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        if(i%10==0){
                            nofity("消息推送测试......");
                            System.out.println("推送消息了....");
                        }else{
                            System.out.println("本次不推送消息了....");
                        }
                        i++;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("失败....");
                }
            }
    
            private void nofity(String message) throws IOException {
                Iterator<WebSocketSession> iterator = sessions.iterator();
                while (iterator.hasNext()) {
                    WebSocketSession session = iterator.next();
                    synchronized(session){
                        if(session.isOpen()){
                            session.sendMessage(new TextMessage(message));
                        }else{
                            iterator.remove();
                        }
                    }
                }
            }
            
        }
    
    }
    

     二.前台界面监听

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    websocket测试界面
    </body>
    <script type="text/javascript">
    
    var websocketPath = "localhost:8080/reyo";
    
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://"+websocketPath+"/ws/notifymessage.ws");
    } else if ('MozWebSocket' in window) {
        websocket = new MozWebSocket("ws://"+websocketPath+"/ws/notifymessage.ws");
    } else {
        websocket = new SockJS("ws://"+websocketPath+"/ws/notifymessage.ws");
    }
    websocket.onopen = function (evnt) {
    };
    websocket.onmessage = function (evnt) {
        console.log(evnt);
    };
    websocket.onerror = function (evnt) {
    };
    websocket.onclose = function (evnt) {
    }
    </script>
    </html>
    

    注意web.xml中配置DispatcherServlet控制器

    spring-servlet.xml空文件
    <servlet>
            <servlet-name>spring</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/spring-servlet.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>spring</servlet-name>
            <url-pattern>*.ws</url-pattern>
        </servlet-mapping>
    
  • 相关阅读:
    Django创建模型。
    Kubernetes APIService资源
    应用系统管理风险
    [Golang] go list命令查看依赖的版本
    [Golang] 升级gin框架和jwtgo
    [Git] 解决git错误 OpenSSL SSL_read: Connection was reset, errno 10054
    [Github] 配置ssh免密码登录解决 You've successfully authenticated, but GitHub does not provide shell access.
    go循环遍历小坑
    Go 字符串拼接6种,最快的方式 strings.builder
    uniapp安卓真机调试提示检测不到手机【解决办法】
  • 原文地址:https://www.cnblogs.com/interdrp/p/7768115.html
Copyright © 2020-2023  润新知