• springboot 中使用websocket简单例子


    gradle 中添加依赖,引入websocket支持

        compile("org.springframework.boot:spring-boot-starter-websocket:${springBootVersion}")

    启用websocket

    package cn.xiaojf.today.ws.configuration;
    
    import cn.xiaojf.today.ws.handler.CountWebSocketHandler;
    import cn.xiaojf.today.ws.interceptor.HandshakeInterceptor;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    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.server.standard.ServerEndpointExporter;
    
    /**
     * websocket 配置
     * @author xiaojf 2017/3/2 9:50.
     */
    @Configuration
    @EnableWebSocket
    public class WebSocketConfig implements WebSocketConfigurer {
    
        @Bean
        public ServerEndpointExporter serverEndpointExporter(ApplicationContext context) {
            return new ServerEndpointExporter();
        }
    
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(new CountWebSocketHandler(), "/web/count").addInterceptors(new HandshakeInterceptor());
        }
    }

    消息拦截处理

    package cn.xiaojf.today.ws.interceptor;
    
    import org.springframework.http.server.ServerHttpRequest;
    import org.springframework.http.server.ServerHttpResponse;
    import org.springframework.web.socket.WebSocketHandler;
    import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
    
    import java.util.Map;
    
    /**
     * 消息拦截处理类
     * @author xiaojf 2017/3/2 10:36.
     */
    public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
        @Override
        public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                       Map<String, Object> attributes) throws Exception {
    
            //解决The extension [x-webkit-deflate-frame] is not supported问题
            if (request.getHeaders().containsKey("Sec-WebSocket-Extensions")) {
                request.getHeaders().set("Sec-WebSocket-Extensions", "permessage-deflate");
            }
    
            System.out.println("Before Handshake");
            return super.beforeHandshake(request, response, wsHandler, attributes);
        }
    
        @Override
        public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Exception ex) {
    
            System.out.println("After Handshake");
            super.afterHandshake(request, response, wsHandler, ex);
        }
    }

    消息处理相应类

    package cn.xiaojf.today.ws.handler;
    
    import com.alibaba.druid.support.json.JSONUtils;
    import org.apache.commons.collections.map.HashedMap;
    import org.springframework.stereotype.Component;
    import org.springframework.web.socket.CloseStatus;
    import org.springframework.web.socket.TextMessage;
    import org.springframework.web.socket.WebSocketSession;
    import org.springframework.web.socket.handler.TextWebSocketHandler;
    
    import java.io.IOException;
    import java.util.*;
    
    /**
     * @author xiaojf 2017/3/2 9:55.
     */
    @Component
    public class CountWebSocketHandler extends TextWebSocketHandler {
        private static long count = 0;
        private static Map<String,WebSocketSession> sessionMap = new HashedMap();
    
        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    //        session.sendMessage(new TextMessage(session.getPrincipal().getName()+",你是第" + (sessionMap.size()) + "位访客")); //p2p
    
            Object parse = JSONUtils.parse(message.getPayload());
    
            Collection<WebSocketSession> sessions = sessionMap.values();
            for (WebSocketSession ws : sessions) {//广播
                ws.sendMessage(message);
            }
    
            sendMessage(sessionMap.keySet(),"你好");
        }
    
        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            sessionMap.put(session.getPrincipal().getName(),session);
            super.afterConnectionEstablished(session);
        }
    
        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
            sessionMap.remove(session.getPrincipal().getName());
            super.afterConnectionClosed(session, status);
        }
    
        /**
         * 发送消息
         * @author xiaojf 2017/3/2 11:43
         */
        public static void sendMessage(String username,String message) throws IOException {
            sendMessage(Arrays.asList(username),Arrays.asList(message));
        }
    
        /**
         * 发送消息
         * @author xiaojf 2017/3/2 11:43
         */
        public static void sendMessage(Collection<String> acceptorList,String message) throws IOException {
            sendMessage(acceptorList,Arrays.asList(message));
        }
    
        /**
         * 发送消息,p2p 群发都支持
         * @author xiaojf 2017/3/2 11:43
         */
        public static void sendMessage(Collection<String> acceptorList, Collection<String> msgList) throws IOException {
            if (acceptorList != null && msgList != null) {
                for (String acceptor : acceptorList) {
                    WebSocketSession session = sessionMap.get(acceptor);
                    if (session != null) {
                        for (String msg : msgList) {
                            session.sendMessage(new TextMessage(msg.getBytes()));
                        }
                    }
                }
            }
        }
    }

    前端js,需要依赖jquery

    require(["jquery","formUtil"], function ($) {
    
        var url = 'ws://'+window.location.host+'/web/count';
        var ws = new WebSocket(url);
        ws.onopen = function(e)
        {
            // ws.send('hello');
        };
    
        ws.onmessage = function(e) {
            alert(e.data);
        };
    
        ws.onerror = function(e) {
            alert(e);
        };
    
        $('body').one('DOMNodeRemoved','#start-help',function (e) {//执行一次以后,自动销毁监听事件
            ws.close();
        });
    
        $('#help-submit').on('click',function () {
            var formData = $('#help-form').serializeJson();
            ws.send(JSON.stringify(formData));
        }) ;
    
    });
  • 相关阅读:
    浅谈聚类算法(K-means)
    多步法求解微分方程数值解
    本学期微分方程数值解课程总结(matlab代码)
    Stone Game
    Two Sum IV
    Insert into a Binary Search Tree
    Subtree of Another Tree
    Leaf-Similar Trees
    Diameter of Binary Tree
    Counting Bits
  • 原文地址:https://www.cnblogs.com/xiaojf/p/6613822.html
Copyright © 2020-2023  润新知