Parcourir la source

更新对webSocket的支持

slambb il y a 4 ans
Parent
commit
b4049dbf11

+ 3 - 3
src/main/java/com/td/boss/BossApplication.java

@@ -113,7 +113,7 @@ class IndexController {
 
         //后端公钥
         String publicKey = RsaUtil.getPublicKey();
-        log.info("后端公钥:" + publicKey);
+        log.info("login后端公钥:" + publicKey);
         modelAndView.addObject("publicKey", publicKey);
 
         return modelAndView;
@@ -126,7 +126,7 @@ class IndexController {
     public void index1(HttpServletResponse response){
         //内部重定向
         try {
-            response.sendRedirect("/index");
+            response.sendRedirect(contextPath+"/index");
         } catch (IOException e) {
             //输出到日志文件中
             log.error(ErrorUtil.errorInfoToString(e));
@@ -154,7 +154,7 @@ class IndexController {
 
         //后端公钥
         String publicKey = RsaUtil.getPublicKey();
-        log.info("后端公钥:" + publicKey);
+        log.info("index后端公钥:" + publicKey);
         modelAndView.addObject("publicKey", publicKey);
 
         return modelAndView;

+ 0 - 34
src/main/java/com/td/boss/aspect/SafetyAspect.java

@@ -167,38 +167,4 @@ public class SafetyAspect {
         }
     }
 
-//
-//    @Pointcut(value = "execution(public * com.td.boss.game.*.controller.*.*(..))")
-//    public void gameAspect(){}
-//
-//    @Before(value = "gameAspect()")
-//    public void gameBefore(JoinPoint joinPoint) throws Exception {
-//        //获取上下文request,获取token并解析
-//        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
-//        HttpServletRequest request = requestAttributes.getRequest();
-//        //todo  token 操作
-//        final String requestHeader = request.getHeader(this.tokenHeader);
-//        String userId = null;
-//        String authToken = null;
-//
-//        if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
-//            authToken = requestHeader.substring(7);
-//            try {
-//                userId = jwtTokenUtil.getUserIdFromToken(authToken);
-//                log.info("userId:{}", userId);
-//                //todo 如果需要校验的话,取本地或者数据库一个userId校验
-//                log.info("validateToken:{}", jwtTokenUtil.validateToken(authToken, userId));
-//                //获取参数并赋值
-//                Object[] args1 = joinPoint.getArgs();
-//            } catch (ExpiredJwtException e) {
-//            }
-//        }else{
-////            throw  new ExpiredJwtException(null,null,"error");
-////            throw new AuthorizeException(ResultEnum.TOKEN_IS_ILLEGAL.getCode(),
-////                    ResultEnum.TOKEN_IS_ILLEGAL.getMessage());
-//        }
-//    }
-
-
-
 }

+ 6 - 3
src/main/java/com/td/boss/config/security/SecurityConfig.java

@@ -56,7 +56,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
     @Override
     public void configure(WebSecurity web) throws Exception {
         // game 走 token验证流程
-        web.ignoring().antMatchers("/game/**");
+        web.ignoring().antMatchers("/game/**","/game_websocket/**");
     }
 
     @Override
@@ -96,12 +96,15 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
                 .permitAll()
                 .and();
         http
+                //"play_back"
+                //.mvcMatcher("/game")
                 //定制url访问权限,动态权限读取,参考:https://www.jianshu.com/p/0a06496e75ea
                 .addFilterAfter(dynamicallyUrlInterceptor(), FilterSecurityInterceptor.class)
                 .authorizeRequests()
                 //无需权限访问
-                .antMatchers("/favicon.ico","/common/**", "/webjars/**", "/getVerifyCodeImage","/error/*").permitAll()
-                //其他接口需要登录后才能访问
+                .antMatchers("/favicon.ico","/common/**", "/webjars/**", "/getVerifyCodeImage","/error/*"
+                ).permitAll()
+                 //其他接口需要登录后才能访问
                 .anyRequest().authenticated()
                 .and();
         http.sessionManagement()

+ 1 - 1
src/main/java/com/td/boss/config/token/WebConfig.java

@@ -25,7 +25,7 @@ public class WebConfig {
     public FilterRegistrationBean authorizeFilterRegistration() {
         FilterRegistrationBean registration = new FilterRegistrationBean();
         registration.setFilter(new DelegatingFilterProxy("gameFilter"));
-        registration.addUrlPatterns("/*");
+        registration.addUrlPatterns("/game/*");
         registration.setName("gameFilter");
         registration.setOrder(1);
         return registration;

+ 3 - 0
src/main/java/com/td/boss/config/websocket/WebSocketConfig.java

@@ -2,6 +2,7 @@ package com.td.boss.config.websocket;
 
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
+import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
 import org.springframework.web.socket.server.standard.ServerEndpointExporter;
 
 /**
@@ -27,4 +28,6 @@ public class WebSocketConfig {
     public MyEndpointConfigure newMyEndpointConfigure (){
         return new MyEndpointConfigure ();
     }
+
+
 }

+ 14 - 10
src/main/java/com/td/boss/filter/gameFilter.java

@@ -44,21 +44,25 @@ public class gameFilter implements Filter {
         response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
         response.setHeader("Access-Control-Max-Age", "3600");
         response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept , Authorization");
-//        log.info("********进入过滤器********");
+
+        log.info("********进入过滤器********");
         HttpServletRequest req = (HttpServletRequest) servletRequest;
-        String method = req.getMethod();
-        if (method.equals("OPTIONS")) {
-            response.setStatus(200);
-            response.flushBuffer();
-            return;
-        }
+        //String method = req.getMethod();
+        //if (method.equals("OPTIONS")) {
+        //    response.setStatus(200);
+        //    response.flushBuffer();
+        //    return;
+        //}
         String token = req.getHeader(tokenHeader);
         String path = req.getServletPath();
         //登录,获取验证码,不用登录的接口
-        if (!(path.indexOf("game") > -1)
+        if (!(path.indexOf("game") > -1) // 存在game字段,需要检验token
                 || path.indexOf("loginToken") > -1
-                || path.indexOf("publicKeyAndSys") > -1
-                || path.indexOf("playback")>-1) {
+               // || path.indexOf("publicKeyAndSys") > -1
+               // || path.indexOf("playback")>-1
+                || path.indexOf("game_websocket") > -1 // todo 暂时放行
+
+           ) {
             //登录情况直接放行
             filterChain.doFilter(servletRequest, response);
             return;

+ 1 - 10
src/main/java/com/td/boss/game/comusers/controller/ComUsersController.java

@@ -2,7 +2,7 @@ package com.td.boss.game.comusers.controller;
 
 import com.td.boss.common.controller.*;
 import com.td.boss.common.pojo.Result;
-import com.td.boss.config.dappBack.DappWSServer;
+import com.td.boss.game.dappWs.DappWSServer;
 import com.td.boss.config.enums.ResultEnum;
 import com.td.boss.game.comusers.pojo.ComUsers;
 import com.td.boss.game.comusers.vo.ComUsersVo;
@@ -10,23 +10,14 @@ import com.td.boss.game.comusers.service.ComUsersService;
 import com.td.boss.sys.syssetting.vo.SysSettingVo;
 import com.td.boss.util.JwtTokenUtil;
 import com.td.boss.util.RsaUtil;
-import com.td.boss.util.RunScript;
 import com.td.boss.util.SysSettingUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
-import org.springframework.core.io.ClassPathResource;
 import org.springframework.core.io.Resource;
-import org.springframework.util.ResourceUtils;
 import org.springframework.web.bind.annotation.*;
-import sun.applet.Main;
 
-import javax.script.Invocable;
-import javax.script.ScriptEngine;
-import javax.script.ScriptEngineManager;
 import javax.script.ScriptException;
-import java.io.File;
-import java.io.FileReader;
 import java.io.IOException;
 import java.util.HashMap;
 import java.util.Map;

+ 2 - 5
src/main/java/com/td/boss/config/dappBack/DappWSServer.java → src/main/java/com/td/boss/game/dappWs/DappWSServer.java

@@ -1,14 +1,11 @@
-package com.td.boss.config.dappBack;
+package com.td.boss.game.dappWs;
 import com.td.boss.config.websocket.MyEndpointConfigure;
-import com.td.boss.util.ErrorUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Component;
 import javax.websocket.*;
 import javax.websocket.server.PathParam;
 import javax.websocket.server.ServerEndpoint;
 import java.io.IOException;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.CopyOnWriteArraySet;
 
 /**
@@ -16,7 +13,7 @@ import java.util.concurrent.CopyOnWriteArraySet;
  */
 @Slf4j
 @Component
-@ServerEndpoint(value = "/websocket/dappBack/{sid}", configurator = MyEndpointConfigure.class)
+@ServerEndpoint(value = "/game_websocket/play_back/{sid}", configurator = MyEndpointConfigure.class)
 public class DappWSServer {
 
     //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。

+ 28 - 5
src/main/resources/application.yml

@@ -10,7 +10,7 @@ server:
 #基础配置
 spring:
   profiles:
-    active: ${BASE_ADMIN:dev} #选择配置分支,先读取系统环境变量,如果没有则默认值为 dev
+    active: local #${BASE_ADMIN:prod} #选择配置分支,先读取系统环境变量,如果没有则默认值为 prod
   application:
     name: base-admin
 
@@ -43,6 +43,30 @@ jwt:
 captcha:
   enable: false
 
+---
+##### local 配置 #######
+spring:
+  profiles: local
+
+  #数据库配置
+  datasource:
+    #    42.192.165.168 localhost
+    url: jdbc:mysql://42.192.165.168:3306/dragon_town?serverTimezone=GMT%2B8&characterEncoding=utf-8
+    username: root #dragon_town #root
+    password:  9ab8fad748dead93 #zddeiBmp8c5T6TR6 #9ab8fad748dead93
+    driver-class-name: com.mysql.cj.jdbc.Driver
+    hikari:
+      minimum-idle: 5
+      maximum-pool-size: 15
+      auto-commit: true
+      idle-timeout: 30000
+      max-lifetime: 120000
+      connection-timeout: 30000
+      connection-test-query: SELECT 1
+#是否需要输入验证码
+captcha:
+  enable: false
+
 ---
 ##### dev 配置 #######
 spring:
@@ -50,10 +74,9 @@ spring:
 
   #数据库配置
   datasource:
-    #    42.192.165.168
-    url: jdbc:mysql://localhost:3306/dragon_town?serverTimezone=GMT%2B8&characterEncoding=utf-8
-    username: dragon_town #root
-    password: zddeiBmp8c5T6TR6 #9ab8fad748dead93
+    url: jdbc:mysql://42.192.165.168:3306/dragon_town?serverTimezone=GMT%2B8&characterEncoding=utf-8
+    username: root #dragon_town #root
+    password: 9ab8fad748dead93 #zddeiBmp8c5T6TR6 #9ab8fad748dead93
     driver-class-name: com.mysql.cj.jdbc.Driver
     hikari:
       minimum-idle: 5

+ 25 - 0
src/main/resources/logback-spring.xml

@@ -55,6 +55,20 @@
     </appender>
 
     <!-- 多环境配置 按照active profile选择分支 -->
+    <springProfile name="local">
+
+        <!--root节点 全局日志级别,用来指定最基础的日志输出级别-->
+        <root level="INFO">
+            <appender-ref ref="FILE"/>
+            <appender-ref ref="CONSOLE"/>
+        </root>
+
+        <!-- 子节点向上级传递 局部日志级别-->
+        <logger level="WARN" name="org.springframework"/>
+        <logger level="WARN" name="com.netflix"/>
+        <logger level="DEBUG" name="org.hibernate.SQL"/>
+
+    </springProfile>
     <springProfile name="dev">
         <!--root节点 全局日志级别,用来指定最基础的日志输出级别-->
         <root level="INFO">
@@ -69,5 +83,16 @@
     </springProfile>
     <springProfile name="prod">
 
+        <!--root节点 全局日志级别,用来指定最基础的日志输出级别-->
+        <root level="INFO">
+            <appender-ref ref="FILE"/>
+            <appender-ref ref="CONSOLE"/>
+        </root>
+
+        <!-- 子节点向上级传递 局部日志级别-->
+        <logger level="WARN" name="org.springframework"/>
+        <logger level="WARN" name="com.netflix"/>
+        <logger level="DEBUG" name="org.hibernate.SQL"/>
+
     </springProfile>
 </configuration>

+ 2 - 2
src/main/resources/view/logging.html

@@ -39,8 +39,8 @@
         //动态获取域名或ip
         let hostname = window.location.hostname;
         port = window.location.port;
-        websocket = new WebSocket("ws://"+hostname+":" + port + ctx + "/websocket/logging");
-        console.log("ws://"+hostname+":" + port + ctx + "/websocket/logging");
+        websocket = new WebSocket("wss://"+hostname+":" + port + ctx + "/websocket/logging");
+        console.log("wss://"+hostname+":" + port + ctx + "/websocket/logging");
     } else {
         console.error("不支持WebSocket");
     }

+ 1 - 1
src/main/resources/view/monitor.html

@@ -95,7 +95,7 @@
         //动态获取域名或ip
         let hostname = window.location.hostname;
         port = window.location.port;
-        websocket = new WebSocket("ws://"+hostname+":" + port + ctx + "/websocket/monitor");
+        websocket = new WebSocket("wss://"+hostname+":" + port + ctx + "/websocket/monitor");
     } else {
         console.error("不支持WebSocket");
     }

BIN
target/SNTown-0.10.jar