• springcloudgateway转发websocket


    一,前端页面

      1.原生请求

    //建立连接
    this.websocket = new WebSocket('ws://localhost:8085/websocket/user?token='+auth);
      //接收
       this.websocket.onmessage = function(e){
         console.log(e.data);
       }
    //发送
    this.websocket.send(text);

      2.sockJS请求

    //建立连接
    var sock = new SockJS('http://localhost:8085/websocket',null,{timeout: 30000});
    var stomp = Stomp.over(sock);
    var headers = {
    login: 'mylogin',
    passcode: 'mypasscode',
    'client-id': 'my-client-id',
    'Authorization':auth};
    stomp.connect(headers,
        function(frame){    
    //订阅主题 stomp.subscribe(
    '/user/updateInfo',(resp)=>{ console.log(resp.body); resp.ack(); });
    //发送 stomp.send("/user", {'Authorization': auth},payload);

    二,gateway配置

    
    
    spring:
      cloud:
        gateway:
          routes:
          # SockJS首次info路由
          - id: websocket_sockjs_route
            uri: lb://testService
            predicates:
            - Path=/websocket/info/**
          # Websocket原生路由
          - id: websocket_route
            uri: lb:ws://testService
            predicates:
            - Path=/websocket/**

    三,服务端

      1.tomcat实现

    @Configuration
    public class WebsocketConfig {
    
        @Bean
        public ServerEndpointExporter serverEndpointExporter( ) {
           return new ServerEndpointExporter();
        }
    }
    
    @Component
    @ServerEndpoint("/websocket/user")
    public class WebsocketController {
    
        Session testSession = null;
    
        @OnOpen
        public void onOpen(Session session){
    
            testSession = session;
    
            System.out.println("ws connected!!");
            sendMessage("ws connected!!");
        }
    
        @OnMessage
        public void onMessage(String msg,Session session){
            System.out.println("msg '" +msg+ "' received!!");
    
            try {
                sendMessage("msg '" +msg+ "' received!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        public void sendMessage(String msg) {
            try {
                this.testSession.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @OnClose
        public void onClose(Session session){
            System.out.println("ws closed!!");
        }
    
    }

      2.spring实现

      

    @Configuration
    @EnableWebSocket
    public class WebsocketSpringConfig implements WebSocketConfigurer {
    
    
    
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(new WebsocketSpringController(),"/websocket/user").addInterceptors(new WebsocketInterceptor()).setAllowedOrigins("http://localhost");
        }
    }
    
    public class WebsocketInterceptor implements HandshakeInterceptor {
        @Override
        public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
            map.put("token","");
            return true;
        }
    
        @Override
        public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        }
    }
    
    
    public class WebsocketSpringController extends TextWebSocketHandler {
    
        private final String charset = "UTF-8";
        private WebSocketSession session;
    
        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            this.session = session;
            System.out.println(session);
            session.sendMessage(new TextMessage("connected..."));
    
        }
    
        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            String payload = message.getPayload();
            System.out.println(payload);
            session.sendMessage(new TextMessage("received:" + payload));
    
        }
    
        @Override
        public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
            super.handleTransportError(session, exception);
        }
    
        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
            super.afterConnectionClosed(session, status);
        }
    }
  • 相关阅读:
    BZOJ 3881: [Coci2015]Divljak
    BZOJ 2434: [Noi2011]阿狸的打字机
    BZOJ 2580: [Usaco2012 Jan]Video Game
    BZOJ 3940: [Usaco2015 Feb]Censoring
    BZOJ 3942: [Usaco2015 Feb]Censoring
    PTA L2-002 链表去重 团体程序设计天梯赛-练习集
    PTA L2-001 紧急救援-最短路(Dijkstra)多条最短路找最优解并输出路径 团体程序设计天梯赛-练习集
    PTA L1-020 帅到没朋友 团体程序设计天梯赛-练习集
    Codeforces 429 B. Working out-dp( Codeforces Round #245 (Div. 1))
    HDU 6467.简单数学题-数学题 (“字节跳动-文远知行杯”广东工业大学第十四届程序设计竞赛)
  • 原文地址:https://www.cnblogs.com/uip001/p/15848937.html
Copyright © 2020-2023  润新知