├── src └── main │ ├── resources │ └── META-INF │ │ ├── spring │ │ └── org.springframework.boot.autoconfigure.AutoConfiguration.imports │ │ └── spring.factories │ └── java │ └── cn │ └── twelvet │ └── websocket │ └── netty │ ├── autoconfigure │ ├── NettyWebSocketAutoConfigure.java │ ├── annotation │ │ └── EnableWebSocket.java │ └── NettyWebSocketSelector.java │ ├── support │ ├── WsPathMatcher.java │ ├── impl │ │ ├── path │ │ │ ├── DefaultPathMatcher.java │ │ │ └── AntPathMatcherWrapper.java │ │ ├── HttpHeadersMethodArgumentResolver.java │ │ ├── SessionMethodArgumentResolver.java │ │ ├── ThrowableMethodArgumentResolver.java │ │ ├── TextMethodArgumentResolver.java │ │ ├── ByteMethodArgumentResolver.java │ │ ├── EventMethodArgumentResolver.java │ │ ├── PathVariableMapMethodArgumentResolver.java │ │ ├── PathVariableMethodArgumentResolver.java │ │ ├── RequestParamMapMethodArgumentResolver.java │ │ └── RequestParamMethodArgumentResolver.java │ └── MethodArgumentResolver.java │ ├── annotation │ ├── OnBinary.java │ ├── OnClose.java │ ├── OnEvent.java │ ├── OnMessage.java │ ├── OnError.java │ ├── OnOpen.java │ ├── BeforeHandshake.java │ ├── PathVariable.java │ ├── RequestParam.java │ └── WebSocketEndpoint.java │ ├── exception │ └── WebSocketException.java │ ├── standard │ ├── EndpointClassPathScanner.java │ ├── handler │ │ ├── WebSocketServerHandler.java │ │ └── HttpServerHandler.java │ ├── WebsocketServer.java │ ├── WebSocketEndpointConfig.java │ └── WebSocketEndpointExporter.java │ ├── util │ └── SslUtils.java │ └── domain │ ├── NettySession.java │ ├── WebSocketEndpointServer.java │ └── WebSocketMethodMapping.java ├── .github └── workflows │ ├── test.yml │ └── oss-release-deploy.yml ├── .gitignore ├── README_ZH.md ├── README.md ├── LICENSE └── pom.xml /src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports: -------------------------------------------------------------------------------- 1 | cn.twelvet.websocket.netty.autoconfigure.NettyWebSocketAutoConfigure 2 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 2 | cn.twelvet.websocket.netty.autoconfigure.NettyWebSocketAutoConfigure 3 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/autoconfigure/NettyWebSocketAutoConfigure.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.autoconfigure; 2 | 3 | import cn.twelvet.websocket.netty.autoconfigure.annotation.EnableWebSocket; 4 | 5 | /** 6 | * @author twelvet AutoConfigure 7 | */ 8 | @EnableWebSocket 9 | public class NettyWebSocketAutoConfigure { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/support/WsPathMatcher.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.support; 2 | 3 | import io.netty.channel.Channel; 4 | import io.netty.handler.codec.http.QueryStringDecoder; 5 | 6 | /** 7 | * @author twelvet WebSocket path matcher 8 | */ 9 | public interface WsPathMatcher { 10 | 11 | String getPattern(); 12 | 13 | boolean matchAndExtract(QueryStringDecoder decoder, Channel channel); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/annotation/OnBinary.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * @author twelvet 当接收到二进制消息时,对该方法进行回调 注入参数的类型:Session、byte[] 10 | */ 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target(ElementType.METHOD) 13 | public @interface OnBinary { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/annotation/OnClose.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * @author twelvet 当有WebSocket连接关闭时,对该方法进行回调 注入参数的类型:Session 10 | */ 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target(ElementType.METHOD) 13 | public @interface OnClose { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/annotation/OnEvent.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * @author twelvet 当接收到Netty的事件时,对该方法进行回调 注入参数的类型:Session、Object 10 | */ 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target(ElementType.METHOD) 13 | public @interface OnEvent { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/annotation/OnMessage.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * @author twelvet 当接收到字符串消息时,对该方法进行回调 注入参数的类型:Session、String 10 | */ 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target(ElementType.METHOD) 13 | public @interface OnMessage { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/exception/WebSocketException.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.exception; 2 | 3 | /** 4 | * @author twelvet WebSocketException 5 | */ 6 | public class WebSocketException extends Exception { 7 | 8 | private static final long serialVersionUID = 1L; 9 | 10 | public WebSocketException(String message) { 11 | super(message); 12 | } 13 | 14 | public WebSocketException(String message, Throwable cause) { 15 | super(message, cause); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/annotation/OnError.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * @author twelvet 当有WebSocket抛出异常时,对该方法进行回调 注入参数的类型:Session、Throwable 10 | */ 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target(ElementType.METHOD) 13 | public @interface OnError { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/annotation/OnOpen.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * @author twelvet 当有新的WebSocket连接完成时,对该方法进行回调 注入参数的类型:Session、HttpHeaders... 10 | */ 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target(ElementType.METHOD) 13 | public @interface OnOpen { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/annotation/BeforeHandshake.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * @author twelvet 当有新的连接进入之前,对该方法进行回调 注入参数的类型:Session、HttpHeaders... 10 | */ 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target(ElementType.METHOD) 13 | public @interface BeforeHandshake { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: [ master ] 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | strategy: 12 | matrix: 13 | java-version: [ 17 ] 14 | steps: 15 | - uses: actions/checkout@v3 16 | 17 | - name: Set up JDK ${{ matrix.java-version }} 18 | uses: actions/setup-java@v3 19 | with: 20 | java-version: ${{ matrix.java-version }} 21 | distribution: zulu 22 | cache: maven 23 | 24 | - name: mvn spring-javaformat:validate 25 | run: mvn spring-javaformat:validate 26 | 27 | - name: mvn clean install 28 | run: mvn clean install 29 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/autoconfigure/annotation/EnableWebSocket.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.autoconfigure.annotation; 2 | 3 | import cn.twelvet.websocket.netty.autoconfigure.NettyWebSocketSelector; 4 | import org.springframework.context.annotation.Import; 5 | 6 | import java.lang.annotation.ElementType; 7 | import java.lang.annotation.Retention; 8 | import java.lang.annotation.RetentionPolicy; 9 | import java.lang.annotation.Target; 10 | 11 | /** 12 | * @author twelvet 开启WebSocket 13 | */ 14 | @Retention(RetentionPolicy.RUNTIME) 15 | @Target(ElementType.TYPE) 16 | @Import(NettyWebSocketSelector.class) 17 | public @interface EnableWebSocket { 18 | 19 | String[] scanBasePackages() default {}; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/support/impl/path/DefaultPathMatcher.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.support.impl.path; 2 | 3 | import cn.twelvet.websocket.netty.support.WsPathMatcher; 4 | import io.netty.channel.Channel; 5 | import io.netty.handler.codec.http.QueryStringDecoder; 6 | 7 | /** 8 | * @author twelvet Default path matcher 9 | */ 10 | public class DefaultPathMatcher implements WsPathMatcher { 11 | 12 | private final String pattern; 13 | 14 | public DefaultPathMatcher(String pattern) { 15 | this.pattern = pattern; 16 | } 17 | 18 | @Override 19 | public String getPattern() { 20 | return this.pattern; 21 | } 22 | 23 | @Override 24 | public boolean matchAndExtract(QueryStringDecoder decoder, Channel channel) { 25 | return pattern.equals(decoder.path()); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/support/MethodArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.support; 2 | 3 | import io.netty.channel.Channel; 4 | import org.springframework.core.MethodParameter; 5 | import org.springframework.lang.Nullable; 6 | 7 | public interface MethodArgumentResolver { 8 | 9 | /** 10 | * Whether the given {@linkplain org.springframework.core.MethodParameter method 11 | * parameter} is supported by this resolver. 12 | * @param parameter the method parameter to check 13 | * @return {@code true} if this resolver supports the supplied parameter; 14 | * {@code false} otherwise 15 | */ 16 | boolean supportsParameter(MethodParameter parameter); 17 | 18 | @Nullable 19 | Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ###################################################################### 2 | # Build Tools 3 | 4 | .gradle 5 | /build/ 6 | !gradle/wrapper/gradle-wrapper.jar 7 | 8 | target/ 9 | !.mvn/wrapper/maven-wrapper.jar 10 | 11 | ###################################################################### 12 | 13 | ### STS ### 14 | .apt_generated 15 | .classpath 16 | .factorypath 17 | .project 18 | .settings 19 | .springBeans 20 | 21 | ### IntelliJ IDEA ### 22 | .idea 23 | *.iws 24 | *.iml 25 | *.ipr 26 | 27 | # log 28 | /logs 29 | 30 | ### NetBeans ### 31 | nbproject/private/ 32 | build/* 33 | nbbuild/ 34 | dist/ 35 | mock/ 36 | nbdist/ 37 | .nb-gradle/ 38 | 39 | ###################################################################### 40 | # Others 41 | *.log 42 | *.xml.versionsBackup 43 | 44 | !*/build/*.java 45 | !*/build/*.html 46 | !*/build/*.xml 47 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/annotation/PathVariable.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.annotation; 2 | 3 | import org.springframework.core.annotation.AliasFor; 4 | 5 | import java.lang.annotation.ElementType; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | 10 | /** 11 | * @author twelvet 获取路径参数(与Spring @PathVariable同理) 12 | */ 13 | @Target(ElementType.PARAMETER) 14 | @Retention(RetentionPolicy.RUNTIME) 15 | public @interface PathVariable { 16 | 17 | /** 18 | * Alias for {@link #name}. 19 | * @return 返回路径 20 | */ 21 | @AliasFor("name") 22 | String value() default ""; 23 | 24 | /** 25 | * The name of the path variable to bind to. 26 | * @return 路径名称 27 | */ 28 | @AliasFor("value") 29 | String name() default ""; 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/autoconfigure/NettyWebSocketSelector.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.autoconfigure; 2 | 3 | import cn.twelvet.websocket.netty.standard.WebSocketEndpointExporter; 4 | import org.springframework.boot.autoconfigure.AutoConfiguration; 5 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.core.io.ResourceLoader; 8 | 9 | /** 10 | * @author twelvet 开启WebSocket 11 | */ 12 | @ConditionalOnMissingBean({ WebSocketEndpointExporter.class }) 13 | @AutoConfiguration 14 | public class NettyWebSocketSelector { 15 | 16 | @Bean 17 | public WebSocketEndpointExporter webSocketEndpointExporter(ResourceLoader resourceLoader) { 18 | return new WebSocketEndpointExporter(resourceLoader); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/support/impl/HttpHeadersMethodArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.support.impl; 2 | 3 | import cn.twelvet.websocket.netty.support.MethodArgumentResolver; 4 | import io.netty.channel.Channel; 5 | import io.netty.handler.codec.http.FullHttpRequest; 6 | import io.netty.handler.codec.http.HttpHeaders; 7 | import org.springframework.core.MethodParameter; 8 | 9 | public class HttpHeadersMethodArgumentResolver implements MethodArgumentResolver { 10 | 11 | @Override 12 | public boolean supportsParameter(MethodParameter parameter) { 13 | return HttpHeaders.class.isAssignableFrom(parameter.getParameterType()); 14 | } 15 | 16 | @Override 17 | public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception { 18 | return ((FullHttpRequest) object).headers(); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/support/impl/SessionMethodArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.support.impl; 2 | 3 | import cn.twelvet.websocket.netty.domain.NettySession; 4 | import cn.twelvet.websocket.netty.support.MethodArgumentResolver; 5 | import io.netty.channel.Channel; 6 | import org.springframework.core.MethodParameter; 7 | 8 | import static cn.twelvet.websocket.netty.domain.WebSocketEndpointServer.SESSION_KEY; 9 | 10 | public class SessionMethodArgumentResolver implements MethodArgumentResolver { 11 | 12 | @Override 13 | public boolean supportsParameter(MethodParameter parameter) { 14 | return NettySession.class.isAssignableFrom(parameter.getParameterType()); 15 | } 16 | 17 | @Override 18 | public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception { 19 | return channel.attr(SESSION_KEY).get(); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/support/impl/ThrowableMethodArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.support.impl; 2 | 3 | import cn.twelvet.websocket.netty.support.MethodArgumentResolver; 4 | import io.netty.channel.Channel; 5 | import org.springframework.core.MethodParameter; 6 | import cn.twelvet.websocket.netty.annotation.OnError; 7 | 8 | public class ThrowableMethodArgumentResolver implements MethodArgumentResolver { 9 | 10 | @Override 11 | public boolean supportsParameter(MethodParameter parameter) { 12 | return parameter.getMethod().isAnnotationPresent(OnError.class) 13 | && Throwable.class.isAssignableFrom(parameter.getParameterType()); 14 | } 15 | 16 | @Override 17 | public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception { 18 | if (object instanceof Throwable) { 19 | return object; 20 | } 21 | return null; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/support/impl/TextMethodArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.support.impl; 2 | 3 | import cn.twelvet.websocket.netty.support.MethodArgumentResolver; 4 | import io.netty.channel.Channel; 5 | import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; 6 | import org.springframework.core.MethodParameter; 7 | import cn.twelvet.websocket.netty.annotation.OnMessage; 8 | 9 | public class TextMethodArgumentResolver implements MethodArgumentResolver { 10 | 11 | @Override 12 | public boolean supportsParameter(MethodParameter parameter) { 13 | return parameter.getMethod().isAnnotationPresent(OnMessage.class) 14 | && String.class.isAssignableFrom(parameter.getParameterType()); 15 | } 16 | 17 | @Override 18 | public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception { 19 | TextWebSocketFrame textFrame = (TextWebSocketFrame) object; 20 | return textFrame.text(); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/standard/EndpointClassPathScanner.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.standard; 2 | 3 | import cn.twelvet.websocket.netty.annotation.WebSocketEndpoint; 4 | import org.springframework.beans.factory.config.BeanDefinitionHolder; 5 | import org.springframework.beans.factory.support.BeanDefinitionRegistry; 6 | import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; 7 | import org.springframework.core.type.filter.AnnotationTypeFilter; 8 | 9 | import java.util.Set; 10 | 11 | /** 12 | * @author twelvet 根据路径扫描端点 13 | */ 14 | public class EndpointClassPathScanner extends ClassPathBeanDefinitionScanner { 15 | 16 | public EndpointClassPathScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) { 17 | super(registry, useDefaultFilters); 18 | } 19 | 20 | /** 21 | * add scan endpoint 22 | * @param basePackages package 23 | * @return Set 24 | */ 25 | @Override 26 | protected Set doScan(String... basePackages) { 27 | // add scan 28 | addIncludeFilter(new AnnotationTypeFilter(WebSocketEndpoint.class)); 29 | return super.doScan(basePackages); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/support/impl/ByteMethodArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.support.impl; 2 | 3 | import cn.twelvet.websocket.netty.support.MethodArgumentResolver; 4 | import io.netty.buffer.ByteBuf; 5 | import io.netty.channel.Channel; 6 | import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; 7 | import org.springframework.core.MethodParameter; 8 | import cn.twelvet.websocket.netty.annotation.OnBinary; 9 | 10 | public class ByteMethodArgumentResolver implements MethodArgumentResolver { 11 | 12 | @Override 13 | public boolean supportsParameter(MethodParameter parameter) { 14 | return parameter.getMethod().isAnnotationPresent(OnBinary.class) 15 | && byte[].class.isAssignableFrom(parameter.getParameterType()); 16 | } 17 | 18 | @Override 19 | public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception { 20 | BinaryWebSocketFrame binaryWebSocketFrame = (BinaryWebSocketFrame) object; 21 | ByteBuf content = binaryWebSocketFrame.content(); 22 | byte[] bytes = new byte[content.readableBytes()]; 23 | content.readBytes(bytes); 24 | return bytes; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /.github/workflows/oss-release-deploy.yml: -------------------------------------------------------------------------------- 1 | name: publish maven package 2 | on: 3 | workflow_dispatch: 4 | 5 | jobs: 6 | oss-release-deploy: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: Checkout 10 | uses: actions/checkout@v3 11 | - name: Set up JDK 17 12 | uses: actions/setup-java@v3 13 | with: 14 | java-version: '17' 15 | distribution: 'adopt' 16 | cache: maven 17 | 18 | - name: Setup Maven Central 19 | uses: actions/setup-java@v3 20 | with: # overwrite settings.xml 21 | java-version: '17' 22 | distribution: 'adopt' 23 | server-id: ossrh 24 | server-username: OSSRH_USERNAME 25 | server-password: OSSRH_PASSWORD 26 | gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} 27 | gpg-passphrase: MAVEN_GPG_PASSPHRASE 28 | 29 | - name: Publish to Maven Central 30 | run: mvn clean deploy -P release -Dmaven.test.skip=true 31 | env: 32 | MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} 33 | OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} 34 | OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} 35 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/support/impl/path/AntPathMatcherWrapper.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.support.impl.path; 2 | 3 | import cn.twelvet.websocket.netty.support.WsPathMatcher; 4 | import io.netty.channel.Channel; 5 | import io.netty.handler.codec.http.QueryStringDecoder; 6 | import org.springframework.util.AntPathMatcher; 7 | 8 | import java.util.LinkedHashMap; 9 | import java.util.Map; 10 | 11 | import static cn.twelvet.websocket.netty.domain.WebSocketEndpointServer.URI_TEMPLATE; 12 | 13 | /** 14 | * @author twelvet Ant path matcher 15 | */ 16 | public class AntPathMatcherWrapper extends AntPathMatcher implements WsPathMatcher { 17 | 18 | private final String pattern; 19 | 20 | public AntPathMatcherWrapper(String pattern) { 21 | this.pattern = pattern; 22 | } 23 | 24 | @Override 25 | public String getPattern() { 26 | return this.pattern; 27 | } 28 | 29 | @Override 30 | public boolean matchAndExtract(QueryStringDecoder decoder, Channel channel) { 31 | Map variables = new LinkedHashMap<>(); 32 | boolean result = doMatch(pattern, decoder.path(), true, variables); 33 | if (result) { 34 | channel.attr(URI_TEMPLATE).set(variables); 35 | return true; 36 | } 37 | return false; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/support/impl/EventMethodArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.support.impl; 2 | 3 | import cn.twelvet.websocket.netty.support.MethodArgumentResolver; 4 | import io.netty.channel.Channel; 5 | import org.springframework.beans.TypeConverter; 6 | import org.springframework.beans.factory.support.AbstractBeanFactory; 7 | import org.springframework.core.MethodParameter; 8 | import cn.twelvet.websocket.netty.annotation.OnEvent; 9 | 10 | public class EventMethodArgumentResolver implements MethodArgumentResolver { 11 | 12 | private final AbstractBeanFactory beanFactory; 13 | 14 | public EventMethodArgumentResolver(AbstractBeanFactory beanFactory) { 15 | this.beanFactory = beanFactory; 16 | } 17 | 18 | @Override 19 | public boolean supportsParameter(MethodParameter parameter) { 20 | return parameter.getMethod().isAnnotationPresent(OnEvent.class); 21 | } 22 | 23 | @Override 24 | public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception { 25 | if (object == null) { 26 | return null; 27 | } 28 | TypeConverter typeConverter = beanFactory.getTypeConverter(); 29 | return typeConverter.convertIfNecessary(object, parameter.getParameterType()); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/annotation/RequestParam.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.annotation; 2 | 3 | import org.springframework.core.annotation.AliasFor; 4 | 5 | import java.lang.annotation.ElementType; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | 10 | /** 11 | * @author twelvet 获取参数(与Spring @RequestParam 同理) 12 | */ 13 | @Target(ElementType.PARAMETER) 14 | @Retention(RetentionPolicy.RUNTIME) 15 | public @interface RequestParam { 16 | 17 | /** 18 | * Alias for {@link #name}. 19 | * @return 所需参数 20 | */ 21 | @AliasFor("name") 22 | String value() default ""; 23 | 24 | /** 25 | * The name of the request parameter to bind to. 26 | * @return 所需参数 27 | */ 28 | @AliasFor("value") 29 | String name() default ""; 30 | 31 | /** 32 | * Whether the parameter is required. 33 | *

34 | * Defaults to {@code true}, leading to an exception being thrown if the parameter is 35 | * missing in the request. Switch this to {@code false} if you prefer a {@code null} 36 | * value if the parameter is not present in the request. 37 | *

38 | * Alternatively, provide a {@link #defaultValue}, which implicitly sets this flag to 39 | * {@code false}. 40 | * @return 是否必须的 41 | */ 42 | boolean required() default true; 43 | 44 | /** 45 | * The default value to use as a fallback when the request parameter is not provided 46 | * or has an empty value. 47 | *

48 | * Supplying a default value implicitly sets {@link #required} to {@code false}. 49 | * @return 默认信息 50 | */ 51 | String defaultValue() default "\n\t\t\n\t\t\n\uE000\uE001\uE002\n\t\t\t\t\n"; 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/support/impl/PathVariableMapMethodArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.support.impl; 2 | 3 | import cn.twelvet.websocket.netty.support.MethodArgumentResolver; 4 | import io.netty.channel.Channel; 5 | import org.springframework.core.MethodParameter; 6 | import org.springframework.util.CollectionUtils; 7 | import org.springframework.util.StringUtils; 8 | import cn.twelvet.websocket.netty.annotation.PathVariable; 9 | 10 | import java.util.Collections; 11 | import java.util.Map; 12 | 13 | import static cn.twelvet.websocket.netty.domain.WebSocketEndpointServer.URI_TEMPLATE; 14 | 15 | public class PathVariableMapMethodArgumentResolver implements MethodArgumentResolver { 16 | 17 | @Override 18 | public boolean supportsParameter(MethodParameter parameter) { 19 | PathVariable ann = parameter.getParameterAnnotation(PathVariable.class); 20 | return (ann != null && Map.class.isAssignableFrom(parameter.getParameterType()) 21 | && !StringUtils.hasText(ann.value())); 22 | } 23 | 24 | @Override 25 | public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception { 26 | PathVariable ann = parameter.getParameterAnnotation(PathVariable.class); 27 | String name = ann.name(); 28 | if (name.isEmpty()) { 29 | name = parameter.getParameterName(); 30 | if (name == null) { 31 | throw new IllegalArgumentException( 32 | "Name for argument type [" + parameter.getNestedParameterType().getName() 33 | + "] not available, and parameter name information not found in class file either."); 34 | } 35 | } 36 | Map uriTemplateVars = channel.attr(URI_TEMPLATE).get(); 37 | if (!CollectionUtils.isEmpty(uriTemplateVars)) { 38 | return uriTemplateVars; 39 | } 40 | else { 41 | return Collections.emptyMap(); 42 | } 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/support/impl/PathVariableMethodArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.support.impl; 2 | 3 | import cn.twelvet.websocket.netty.support.MethodArgumentResolver; 4 | import io.netty.channel.Channel; 5 | import org.springframework.beans.TypeConverter; 6 | import org.springframework.beans.factory.support.AbstractBeanFactory; 7 | import org.springframework.core.MethodParameter; 8 | import cn.twelvet.websocket.netty.annotation.PathVariable; 9 | 10 | import java.util.Map; 11 | 12 | import static cn.twelvet.websocket.netty.domain.WebSocketEndpointServer.URI_TEMPLATE; 13 | 14 | public class PathVariableMethodArgumentResolver implements MethodArgumentResolver { 15 | 16 | private final AbstractBeanFactory beanFactory; 17 | 18 | public PathVariableMethodArgumentResolver(AbstractBeanFactory beanFactory) { 19 | this.beanFactory = beanFactory; 20 | } 21 | 22 | @Override 23 | public boolean supportsParameter(MethodParameter parameter) { 24 | return parameter.hasParameterAnnotation(PathVariable.class); 25 | } 26 | 27 | @Override 28 | public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception { 29 | PathVariable ann = parameter.getParameterAnnotation(PathVariable.class); 30 | String name = ann.name(); 31 | if (name.isEmpty()) { 32 | name = parameter.getParameterName(); 33 | if (name == null) { 34 | throw new IllegalArgumentException( 35 | "Name for argument type [" + parameter.getNestedParameterType().getName() 36 | + "] not available, and parameter name information not found in class file either."); 37 | } 38 | } 39 | Map uriTemplateVars = channel.attr(URI_TEMPLATE).get(); 40 | Object arg = (uriTemplateVars != null ? uriTemplateVars.get(name) : null); 41 | TypeConverter typeConverter = beanFactory.getTypeConverter(); 42 | return typeConverter.convertIfNecessary(arg, parameter.getParameterType()); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/support/impl/RequestParamMapMethodArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.support.impl; 2 | 3 | import cn.twelvet.websocket.netty.support.MethodArgumentResolver; 4 | import io.netty.channel.Channel; 5 | import io.netty.handler.codec.http.FullHttpRequest; 6 | import io.netty.handler.codec.http.QueryStringDecoder; 7 | import org.springframework.core.MethodParameter; 8 | import org.springframework.util.LinkedMultiValueMap; 9 | import org.springframework.util.MultiValueMap; 10 | import org.springframework.util.StringUtils; 11 | import cn.twelvet.websocket.netty.annotation.RequestParam; 12 | 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | import static cn.twelvet.websocket.netty.domain.WebSocketEndpointServer.REQUEST_PARAM; 17 | 18 | public class RequestParamMapMethodArgumentResolver implements MethodArgumentResolver { 19 | 20 | @Override 21 | public boolean supportsParameter(MethodParameter parameter) { 22 | RequestParam requestParam = parameter.getParameterAnnotation(RequestParam.class); 23 | return (requestParam != null && Map.class.isAssignableFrom(parameter.getParameterType()) 24 | && !StringUtils.hasText(requestParam.name())); 25 | } 26 | 27 | @Override 28 | public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception { 29 | RequestParam ann = parameter.getParameterAnnotation(RequestParam.class); 30 | String name = ann.name(); 31 | if (name.isEmpty()) { 32 | name = parameter.getParameterName(); 33 | if (name == null) { 34 | throw new IllegalArgumentException( 35 | "Name for argument type [" + parameter.getNestedParameterType().getName() 36 | + "] not available, and parameter name information not found in class file either."); 37 | } 38 | } 39 | 40 | if (!channel.hasAttr(REQUEST_PARAM)) { 41 | QueryStringDecoder decoder = new QueryStringDecoder(((FullHttpRequest) object).uri()); 42 | channel.attr(REQUEST_PARAM).set(decoder.parameters()); 43 | } 44 | 45 | Map> requestParams = channel.attr(REQUEST_PARAM).get(); 46 | MultiValueMap multiValueMap = new LinkedMultiValueMap<>(requestParams); 47 | if (MultiValueMap.class.isAssignableFrom(parameter.getParameterType())) { 48 | return multiValueMap; 49 | } 50 | else { 51 | return multiValueMap.toSingleValueMap(); 52 | } 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/support/impl/RequestParamMethodArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.support.impl; 2 | 3 | import cn.twelvet.websocket.netty.support.MethodArgumentResolver; 4 | import io.netty.channel.Channel; 5 | import io.netty.handler.codec.http.FullHttpRequest; 6 | import io.netty.handler.codec.http.QueryStringDecoder; 7 | import org.springframework.beans.TypeConverter; 8 | import org.springframework.beans.factory.support.AbstractBeanFactory; 9 | import org.springframework.core.MethodParameter; 10 | import cn.twelvet.websocket.netty.annotation.RequestParam; 11 | 12 | import java.util.List; 13 | import java.util.Map; 14 | 15 | import static cn.twelvet.websocket.netty.domain.WebSocketEndpointServer.REQUEST_PARAM; 16 | 17 | public class RequestParamMethodArgumentResolver implements MethodArgumentResolver { 18 | 19 | private AbstractBeanFactory beanFactory; 20 | 21 | public RequestParamMethodArgumentResolver(AbstractBeanFactory beanFactory) { 22 | this.beanFactory = beanFactory; 23 | } 24 | 25 | @Override 26 | public boolean supportsParameter(MethodParameter parameter) { 27 | return parameter.hasParameterAnnotation(RequestParam.class); 28 | } 29 | 30 | @Override 31 | public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception { 32 | RequestParam ann = parameter.getParameterAnnotation(RequestParam.class); 33 | assert ann != null; 34 | String name = ann.name(); 35 | if (name.isEmpty()) { 36 | name = parameter.getParameterName(); 37 | if (name == null) { 38 | throw new IllegalArgumentException( 39 | "Name for argument type [" + parameter.getNestedParameterType().getName() 40 | + "] not available, and parameter name information not found in class file either."); 41 | } 42 | } 43 | 44 | if (!channel.hasAttr(REQUEST_PARAM)) { 45 | QueryStringDecoder decoder = new QueryStringDecoder(((FullHttpRequest) object).uri()); 46 | channel.attr(REQUEST_PARAM).set(decoder.parameters()); 47 | } 48 | 49 | Map> requestParams = channel.attr(REQUEST_PARAM).get(); 50 | List arg = (requestParams != null ? requestParams.get(name) : null); 51 | TypeConverter typeConverter = beanFactory.getTypeConverter(); 52 | if (arg == null) { 53 | if ("\n\t\t\n\t\t\n\uE000\uE001\uE002\n\t\t\t\t\n".equals(ann.defaultValue())) { 54 | return null; 55 | } 56 | else { 57 | return typeConverter.convertIfNecessary(ann.defaultValue(), parameter.getParameterType()); 58 | } 59 | } 60 | if (List.class.isAssignableFrom(parameter.getParameterType())) { 61 | return typeConverter.convertIfNecessary(arg, parameter.getParameterType()); 62 | } 63 | else { 64 | return typeConverter.convertIfNecessary(arg.get(0), parameter.getParameterType()); 65 | } 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/standard/handler/WebSocketServerHandler.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.standard.handler; 2 | 3 | import io.netty.channel.ChannelFutureListener; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.SimpleChannelInboundHandler; 6 | import io.netty.handler.codec.http.websocketx.*; 7 | import cn.twelvet.websocket.netty.domain.WebSocketEndpointServer; 8 | 9 | /** 10 | * @author twelvet Handler WebSocketFrame 11 | */ 12 | public class WebSocketServerHandler extends SimpleChannelInboundHandler { 13 | 14 | private final WebSocketEndpointServer webSocketEndpointServer; 15 | 16 | public WebSocketServerHandler(WebSocketEndpointServer webSocketEndpointServer) { 17 | this.webSocketEndpointServer = webSocketEndpointServer; 18 | } 19 | 20 | /** 21 | * Receive message 22 | * @param ctx ChannelHandlerContext 23 | * @param msg FullHttpRequest 24 | */ 25 | @Override 26 | protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception { 27 | handleWebSocketFrame(ctx, msg); 28 | } 29 | 30 | /** 31 | * Processing error 32 | * @param ctx ChannelHandlerContext 33 | * @param cause Throwable 34 | */ 35 | @Override 36 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 37 | webSocketEndpointServer.doOnError(ctx.channel(), cause); 38 | } 39 | 40 | /** 41 | * Close inactive connections 42 | * @param ctx ChannelHandlerContext 43 | */ 44 | @Override 45 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 46 | webSocketEndpointServer.doOnClose(ctx.channel()); 47 | } 48 | 49 | /** 50 | * heartbeat 51 | * @param ctx ChannelHandlerContext 52 | * @param evt Object 53 | */ 54 | @Override 55 | public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { 56 | webSocketEndpointServer.doOnEvent(ctx.channel(), evt); 57 | } 58 | 59 | /** 60 | * Processing different types of messages 61 | * @param ctx ChannelHandlerContext 62 | * @param frame WebSocketFrame 63 | */ 64 | private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { 65 | if (frame instanceof TextWebSocketFrame) { 66 | webSocketEndpointServer.doOnMessage(ctx.channel(), frame); 67 | return; 68 | } 69 | if (frame instanceof PingWebSocketFrame) { 70 | ctx.writeAndFlush(new PongWebSocketFrame(frame.content().retain())); 71 | return; 72 | } 73 | if (frame instanceof CloseWebSocketFrame) { 74 | ctx.writeAndFlush(frame.retainedDuplicate()).addListener(ChannelFutureListener.CLOSE); 75 | return; 76 | } 77 | if (frame instanceof BinaryWebSocketFrame) { 78 | webSocketEndpointServer.doOnBinary(ctx.channel(), frame); 79 | return; 80 | } 81 | if (frame instanceof PongWebSocketFrame) { 82 | return; 83 | } 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/util/SslUtils.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.util; 2 | 3 | import io.netty.handler.ssl.SslContext; 4 | import io.netty.handler.ssl.SslContextBuilder; 5 | import org.springframework.util.ObjectUtils; 6 | import org.springframework.util.ResourceUtils; 7 | import org.springframework.util.StringUtils; 8 | 9 | import javax.net.ssl.KeyManagerFactory; 10 | import javax.net.ssl.SSLException; 11 | import javax.net.ssl.TrustManagerFactory; 12 | import java.net.URL; 13 | import java.security.KeyStore; 14 | 15 | /** 16 | * refer to {@link org.springframework.boot.web.embedded.netty.SslServerCustomizer} 17 | */ 18 | public final class SslUtils { 19 | 20 | public static SslContext createSslContext(String keyPassword, String keyStoreResource, String keyStoreType, 21 | String keyStorePassword, String trustStoreResource, String trustStoreType, String trustStorePassword) 22 | throws SSLException { 23 | SslContextBuilder sslBuilder = SslContextBuilder 24 | .forServer(getKeyManagerFactory(keyStoreType, keyStoreResource, keyPassword, keyStorePassword)) 25 | .trustManager(getTrustManagerFactory(trustStoreType, trustStoreResource, trustStorePassword)); 26 | return sslBuilder.build(); 27 | } 28 | 29 | private static KeyManagerFactory getKeyManagerFactory(String type, String resource, String keyPassword, 30 | String keyStorePassword) { 31 | try { 32 | KeyStore keyStore = loadKeyStore(type, resource, keyStorePassword); 33 | KeyManagerFactory keyManagerFactory = KeyManagerFactory 34 | .getInstance(KeyManagerFactory.getDefaultAlgorithm()); 35 | char[] keyPasswordBytes = (!ObjectUtils.isEmpty(keyPassword) ? keyPassword.toCharArray() : null); 36 | if (keyPasswordBytes == null && !ObjectUtils.isEmpty(keyStorePassword)) { 37 | keyPasswordBytes = keyStorePassword.toCharArray(); 38 | } 39 | keyManagerFactory.init(keyStore, keyPasswordBytes); 40 | return keyManagerFactory; 41 | } 42 | catch (Exception ex) { 43 | throw new IllegalStateException(ex); 44 | } 45 | } 46 | 47 | private static TrustManagerFactory getTrustManagerFactory(String trustStoreType, String trustStoreResource, 48 | String trustStorePassword) { 49 | try { 50 | KeyStore store = loadKeyStore(trustStoreType, trustStoreResource, trustStorePassword); 51 | TrustManagerFactory trustManagerFactory = TrustManagerFactory 52 | .getInstance(TrustManagerFactory.getDefaultAlgorithm()); 53 | trustManagerFactory.init(store); 54 | return trustManagerFactory; 55 | } 56 | catch (Exception ex) { 57 | throw new IllegalStateException(ex); 58 | } 59 | } 60 | 61 | private static KeyStore loadKeyStore(String type, String resource, String password) throws Exception { 62 | type = (ObjectUtils.isEmpty(type) ? "JKS" : type); 63 | if (ObjectUtils.isEmpty(resource)) { 64 | return null; 65 | } 66 | KeyStore store = KeyStore.getInstance(type); 67 | URL url = ResourceUtils.getURL(resource); 68 | store.load(url.openStream(), ObjectUtils.isEmpty(password) ? null : password.toCharArray()); 69 | return store; 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /README_ZH.md: -------------------------------------------------------------------------------- 1 | [中文](https://github.com/twelvet-projects/netty-websocket-spring-boot-starter/blob/master/README_ZH.md) | [English](https://github.com/twelvet-projects/netty-websocket-spring-boot-starter/blob/master/README.md) 2 | # netty-websocket-spring-boot-starter 3 | 4 | 是对原有 [netty-websocket-spring-boot-starter](https://github.com/YeautyYE/netty-websocket-spring-boot-starter) 代码重构和功能增强。 5 | 6 | 非常感谢 `netty-websocket-spring-boot-starter` 作者的分享。 7 | 8 | [![AUR](https://img.shields.io/github/license/twelvet-projects/twelvet)](https://github.com/twelvet-projects/netty-websocket-spring-boot-starter/blob/master/LICENSE) 9 | [![](https://img.shields.io/badge/Author-TwelveT-orange.svg)](https://twelvet.cn) 10 | [![](https://img.shields.io/badge/version-1.0.0-success)](https://github.com/twelvet-projects/netty-websocket-spring-boot-starter) 11 | [![GitHub stars](https://img.shields.io/github/stars/twelvet-projects/netty-websocket-spring-boot-starter.svg?style=social&label=Stars)](https://github.com/twelvet-projects/netty-websocket-spring-boot-starter/stargazers) 12 | [![GitHub forks](https://img.shields.io/github/forks/twelvet-projects/netty-websocket-spring-boot-starter.svg?style=social&label=Fork)](https://github.com/twelvet-projects/netty-websocket-spring-boot-starter/network/members) 13 | [![star](https://gitee.com/twelvet/netty-websocket-spring-boot-starter/badge/star.svg?theme=white)](https://gitee.com/twelvet/netty-websocket-spring-boot-starter/stargazers) 14 | [![fork](https://gitee.com/twelvet/netty-websocket-spring-boot-starter/badge/fork.svg?theme=white)](https://gitee.com/twelvet/netty-websocket-spring-boot-starter/members) 15 | 16 | ### 简介 17 | 在Spring Boot中使用Netty来开发WebSocket服务器,并像spring-websocket注解一样简单且高性能 18 | 19 | ### 要求 20 | - jdk >= 1.8 (兼容jdk 17、21) 21 | 22 | ### 快速开始 23 | 24 | - 添加依赖: 25 | 26 | ```xml 27 | 28 | cn.twelvet 29 | netty-websocket-spring-boot-starter 30 | ${version} 31 | 32 | ``` 33 | 34 | - 在端点类上加上`@WebSocketEndpoint`注解,并在相应的方法上加上`@BeforeHandshake`、`@OnOpen`、`@OnClose`、`@OnError`、`@OnMessage`、`@OnBinary`、`@OnEvent`注解,样例如下: 35 | - @PathVariable获取路径参数 @RequestParam获取query参数,二者皆与Spring的注解效果相同(注意:引入本框架实现的注解,不是Spring的) 36 | 37 | ```java 38 | 39 | import cn.twelvet.websocket.netty.annotation.*; 40 | import cn.twelvet.websocket.netty.domain.NettySession; 41 | import io.netty.handler.codec.http.HttpHeaders; 42 | import io.netty.handler.timeout.IdleStateEvent; 43 | import org.springframework.util.MultiValueMap; 44 | 45 | import java.util.Map; 46 | 47 | @WebSocketEndpoint(path = "/ws") 48 | public class MyWebSocket { 49 | 50 | @BeforeHandshake 51 | public void handshake(NettySession nettySession, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap) { 52 | nettySession.setSubprotocols("stomp"); 53 | if (!"ok".equals(req)) { 54 | System.out.println("Authentication failed!"); 55 | // nettySession.close(); 56 | } 57 | } 58 | 59 | @OnOpen 60 | public void onOpen(NettySession nettySession, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap) { 61 | System.out.println("new connection"); 62 | System.out.println(req); 63 | } 64 | 65 | @OnClose 66 | public void onClose(NettySession nettySession) { 67 | System.out.println("one connection closed"); 68 | } 69 | 70 | @OnError 71 | public void onError(NettySession nettySession, Throwable throwable) { 72 | throwable.printStackTrace(); 73 | } 74 | 75 | @OnMessage 76 | public void onMessage(NettySession nettySession, String message) { 77 | System.out.println(message); 78 | nettySession.sendText("Hello Netty!"); 79 | } 80 | 81 | @OnBinary 82 | public void onBinary(NettySession nettySession, byte[] bytes) { 83 | for (byte b : bytes) { 84 | System.out.println(b); 85 | } 86 | nettySession.sendBinary(bytes); 87 | } 88 | 89 | @OnEvent 90 | public void onEvent(NettySession nettySession, Object evt) { 91 | if (evt instanceof IdleStateEvent) { 92 | IdleStateEvent idleStateEvent = (IdleStateEvent) evt; 93 | switch (idleStateEvent.state()) { 94 | case READER_IDLE: 95 | System.out.println("read idle"); 96 | break; 97 | case WRITER_IDLE: 98 | System.out.println("write idle"); 99 | break; 100 | case ALL_IDLE: 101 | System.out.println("all idle"); 102 | break; 103 | default: 104 | break; 105 | } 106 | } 107 | } 108 | 109 | } 110 | ``` 111 | 112 | - 打开WebSocket客户端,连接到`ws://127.0.0.1:80/ws/xxx` 113 | 114 | ### 多端点服务 115 | - 在[快速启动](#快速开始)的基础上,在多个需要成为端点的类上使用`@WebSocketEndpoint`注解即可 116 | - 可通过`WebSocketEndpointExporter.getAddressWebsocketServerMap()`获取所有端点的地址 117 | - 当地址不同时(即host不同或port不同),使用不同的`ServerBootstrap`实例 118 | - 当地址相同,路径(path)不同时,使用同一个`ServerBootstrap`实例 119 | - 当多个端点服务的port为0时,将使用同一个随机的端口号 120 | - 当多个端点的port和path相同时,host不能设为`"0.0.0.0"`,因为`"0.0.0.0"`意味着绑定所有的host 121 | 122 | ### 通过application.properties进行配置 123 | > 所有参数皆可使用`${...}`占位符获取`application.yml`中的配置。如下: 124 | 125 | - 首先在`@WebSocketEndpoint`注解的属性中使用`${...}`占位符 126 | ```java 127 | @WebSocketEndpoint(host = "${ws.host}", port = "${ws.port}") 128 | public class MyWebSocket { 129 | ... 130 | } 131 | ``` 132 | - 接下来即可在`application.yml`中配置 133 | ``` 134 | ws: 135 | host: 0.0.0.0 136 | port: 80 137 | ``` 138 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [中文](https://github.com/twelvet-projects/netty-websocket-spring-boot-starter/blob/master/README_ZH.md) | [English](https://github.com/twelvet-projects/netty-websocket-spring-boot-starter/blob/master/README.md) 2 | # netty-websocket-spring-boot-starter 3 | 4 | It is a code refactoring and feature enhancement for the original [netty-websocket-spring-boot-starter](https://github.com/YeautyYE/netty-websocket-spring-boot-starter). 5 | 6 | Thank you very much for the author's sharing of `netty-websocket-spring-boot-starter`. 7 | 8 | [![AUR](https://img.shields.io/github/license/twelvet-projects/twelvet)](https://github.com/twelvet-projects/netty-websocket-spring-boot-starter/blob/master/LICENSE) 9 | [![](https://img.shields.io/badge/Author-TwelveT-orange.svg)](https://twelvet.cn) 10 | [![](https://img.shields.io/badge/version-1.0.0-success)](https://github.com/twelvet-projects/netty-websocket-spring-boot-starter) 11 | [![GitHub stars](https://img.shields.io/github/stars/twelvet-projects/netty-websocket-spring-boot-starter.svg?style=social&label=Stars)](https://github.com/twelvet-projects/netty-websocket-spring-boot-starter/stargazers) 12 | [![GitHub forks](https://img.shields.io/github/forks/twelvet-projects/netty-websocket-spring-boot-starter.svg?style=social&label=Fork)](https://github.com/twelvet-projects/netty-websocket-spring-boot-starter/network/members) 13 | [![star](https://gitee.com/twelvet/netty-websocket-spring-boot-starter/badge/star.svg?theme=white)](https://gitee.com/twelvet/netty-websocket-spring-boot-starter/stargazers) 14 | [![fork](https://gitee.com/twelvet/netty-websocket-spring-boot-starter/badge/fork.svg?theme=white)](https://gitee.com/twelvet/netty-websocket-spring-boot-starter/members) 15 | 16 | ### Introduction 17 | Developing a WebSocket server using Netty in Spring Boot, with the simplicity and high performance of spring-websocket annotations. 18 | 19 | ### Requirements 20 | - jdk >= 1.8 (compatible with jdk 17、21) 21 | 22 | ### Quick Start 23 | 24 | - Add dependencies: 25 | 26 | ```xml 27 | 28 | cn.twelvet 29 | netty-websocket-spring-boot-starter 30 | ${version} 31 | 32 | ``` 33 | 34 | - Add the `@WebSocketEndpoint` annotation to the endpoint class, and add the `@BeforeHandshake`、`@OnOpen`、`@OnClose`、`@OnError`、`@OnMessage`、`@OnBinary` and `@OnEvent` annotations to the respective methods. Here's an example: 35 | - Use `@PathVariable` to retrieve path parameters and `@RequestParam` to retrieve query parameters, both of which have the same effect as the corresponding Spring annotations (Note: Use the annotations provided by this framework, not Spring's annotations). 36 | 37 | ```java 38 | 39 | import cn.twelvet.websocket.netty.annotation.*; 40 | import cn.twelvet.websocket.netty.domain.NettySession; 41 | import io.netty.handler.codec.http.HttpHeaders; 42 | import io.netty.handler.timeout.IdleStateEvent; 43 | import org.springframework.util.MultiValueMap; 44 | 45 | import java.util.Map; 46 | 47 | @WebSocketEndpoint(path = "/ws") 48 | public class MyWebSocket { 49 | 50 | @BeforeHandshake 51 | public void handshake(NettySession nettySession, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap) { 52 | nettySession.setSubprotocols("stomp"); 53 | if (!"ok".equals(req)) { 54 | System.out.println("Authentication failed!"); 55 | // nettySession.close(); 56 | } 57 | } 58 | 59 | @OnOpen 60 | public void onOpen(NettySession nettySession, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap) { 61 | System.out.println("new connection"); 62 | System.out.println(req); 63 | } 64 | 65 | @OnClose 66 | public void onClose(NettySession nettySession) { 67 | System.out.println("one connection closed"); 68 | } 69 | 70 | @OnError 71 | public void onError(NettySession nettySession, Throwable throwable) { 72 | throwable.printStackTrace(); 73 | } 74 | 75 | @OnMessage 76 | public void onMessage(NettySession nettySession, String message) { 77 | System.out.println(message); 78 | nettySession.sendText("Hello Netty!"); 79 | } 80 | 81 | @OnBinary 82 | public void onBinary(NettySession nettySession, byte[] bytes) { 83 | for (byte b : bytes) { 84 | System.out.println(b); 85 | } 86 | nettySession.sendBinary(bytes); 87 | } 88 | 89 | @OnEvent 90 | public void onEvent(NettySession nettySession, Object evt) { 91 | if (evt instanceof IdleStateEvent) { 92 | IdleStateEvent idleStateEvent = (IdleStateEvent) evt; 93 | switch (idleStateEvent.state()) { 94 | case READER_IDLE: 95 | System.out.println("read idle"); 96 | break; 97 | case WRITER_IDLE: 98 | System.out.println("write idle"); 99 | break; 100 | case ALL_IDLE: 101 | System.out.println("all idle"); 102 | break; 103 | default: 104 | break; 105 | } 106 | } 107 | } 108 | 109 | } 110 | ``` 111 | 112 | - Open the WebSocket client and connect to `ws://127.0.0.1:80/ws/xxx` 113 | 114 | ### Multi Endpoint 115 | - base on [Quick-Start](#quick-start),use annotation `@WebSocketEndpoint` in classes which hope to become a endpoint. 116 | - you can get all socket addresses in `WebSocketEndpointExporter.getAddressWebsocketServerMap()`. 117 | - when there are different addresses(different host or different port) in WebSocket,they will use different `ServerBootstrap` instance. 118 | - when the addresses are the same,but path is different,they will use the same `ServerBootstrap` instance. 119 | - when multiple port of endpoint is 0 ,they will use the same random port 120 | - when multiple port of endpoint is the same as the path,host can't be set as "0.0.0.0",because it means it binds all of the addresses 121 | 122 | ### Configure using application.properties. 123 | 124 | > All parameters can be obtained from the configuration in `application.yml` using `${...}` placeholders. Here's an example:: 125 | 126 | - First, use `${...}` placeholders in the attributes of the `@WebSocketEndpoint` annotation. 127 | ```java 128 | @WebSocketEndpoint(host = "${ws.host}", port = "${ws.port}") 129 | public class MyWebSocket { 130 | ... 131 | } 132 | ``` 133 | - Next, you can configure it in the `application.yml` file. 134 | ``` 135 | ws: 136 | host: 0.0.0.0 137 | port: 80 138 | ``` 139 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/annotation/WebSocketEndpoint.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.annotation; 2 | 3 | import org.springframework.core.annotation.AliasFor; 4 | 5 | import java.lang.annotation.ElementType; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | 10 | /** 11 | * @author twelvet 当WebSocketEndpointExporter类通过Spring配置进行声明并被使用 12 | * 它将会去扫描带有@WebSocketEndpoint注解的类 被注解的类将被注册成为一个WebSocket端点 所有的配置项都在这个注解的属性中 ( 13 | * 如:@WebSocketEndpoint("/ws") ) 14 | */ 15 | @Retention(RetentionPolicy.RUNTIME) 16 | @Target(ElementType.TYPE) 17 | public @interface WebSocketEndpoint { 18 | 19 | /** 20 | * WebSocket的path 21 | * @return String 22 | */ 23 | @AliasFor("path") 24 | String value() default "/"; 25 | 26 | /** 27 | * WebSocket的path 28 | * @return String 29 | */ 30 | @AliasFor("value") 31 | String path() default "/"; 32 | 33 | /** 34 | * WebSocket的host,"0.0.0.0"即是所有本地地址 35 | * @return String 36 | */ 37 | String host() default "0.0.0.0"; 38 | 39 | /** 40 | * 访问端口 41 | * @return int 42 | */ 43 | String port() default "80"; 44 | 45 | /** 46 | * bossEventLoopGroup的线程数 47 | * @return int 48 | */ 49 | String bossLoopGroupThreads() default "1"; 50 | 51 | /** 52 | * workerEventLoopGroup的线程数 53 | * @return int 54 | */ 55 | String workerLoopGroupThreads() default "0"; 56 | 57 | /** 58 | * 是否添加WebSocketServerCompressionHandler到pipeline 59 | * @return boolean 60 | */ 61 | String useCompressionHandler() default "false"; 62 | 63 | // ------------------------- option ------------------------- 64 | 65 | /** 66 | * 连接超时毫秒数 67 | * @return int 68 | */ 69 | String optionConnectTimeoutMillis() default "30000"; 70 | 71 | /** 72 | * 服务端接受连接的队列长度,如果队列已满,客户端连接将被拒绝 73 | * @return int 74 | */ 75 | String optionSoBacklog() default "128"; 76 | 77 | // ------------------------- childOption ------------------------- 78 | 79 | /** 80 | * 一个Loop写操作执行的最大次数,默认值为16 81 | * 也就是说,对于大数据量的写操作至多进行16次,如果16次仍没有全部写完数据,此时会提交一个新的写任务给EventLoop,任务将在下次调度继续执行 82 | * 这样,其他的写请求才能被响应不会因为单个大数据量写请求而耽误 83 | * @return int 84 | */ 85 | String childOptionWriteSpinCount() default "16"; 86 | 87 | /** 88 | * 写高水位标记,默认值64KB。如果Netty的写缓冲区中的字节超过该值,Channel的isWritable()返回False 89 | * @return int 90 | */ 91 | String childOptionWriteBufferHighWaterMark() default "65536"; 92 | 93 | /** 94 | * 写低水位标记,默认值32KB。 当Netty的写缓冲区中的字节超过高水位之后若下降到低水位,则Channel的isWritable()返回True。 95 | * 写高低水位标记使用户可以控制写入数据速度,从而实现流量控制。 96 | * 推荐做法是:每次调用channel.write(msg)方法首先调用channel.isWritable()判断是否可写。 97 | * @return int 98 | */ 99 | String childOptionWriteBufferLowWaterMark() default "32768"; 100 | 101 | /** 102 | * TCP数据接收缓冲区大小。 该缓冲区即TCP接收滑动窗口,linux操作系统可使用命令:cat /proc/sys/net/ipv4/tcp_rmem查询其大小。 103 | * 一般情况下,该值可由用户在任意时刻设置,但当设置值超过64KB时,需要在连接到远端之前设置。 104 | * @return int 105 | */ 106 | String childOptionSoRcvbuf() default "-1"; 107 | 108 | /** 109 | * TCP数据发送缓冲区大小。 该缓冲区即TCP发送滑动窗口,linux操作系统可使用命令:cat /proc/sys/net/ipv4/tcp_smem查询其大小 110 | * @return int 111 | */ 112 | String childOptionSoSndbuf() default "-1"; 113 | 114 | /** 115 | * 立即发送数据,默认值为Ture(Netty默认为True而操作系统默认为False)。 116 | * 该值设置Nagle算法的启用,改算法将小的碎片数据连接成更大的报文来最小化所发送的报文的数量,如果需要发送一些较小的报文,则需要禁用该算法。 117 | * Netty默认禁用该算法,从而最小化报文传输延时 118 | * @return boolean 119 | */ 120 | String childOptionTcpNodelay() default "true"; 121 | 122 | /** 123 | * 连接保活,默认值为False。 启用该功能时,TCP会主动探测空闲连接的有效性。 124 | * 可以将此功能视为TCP的心跳机制,需要注意的是:默认的心跳间隔是7200s即2小时。Netty默认关闭该功能。 125 | * @return boolean 126 | */ 127 | String childOptionSoKeepalive() default "false"; 128 | 129 | /** 130 | * 关闭Socket的延迟时间,默认值为-1,表示禁用该功能。 -1表示socket.close()方法立即返回,但OS底层会将发送缓冲区全部发送到对端。 131 | * 0表示socket.close()方法立即返回,OS放弃发送缓冲区的数据直接向对端发送RST包,对端收到复位错误。 132 | * 非0整数值表示调用socket.close()方法的线程被阻塞直到延迟时间到或发送缓冲区中的数据发送完毕,若超时,则对端会收到复位错误。 133 | * @return int 134 | */ 135 | String childOptionSoLinger() default "-1"; 136 | 137 | /** 138 | * 一个连接的远端关闭时本地端是否关闭,默认值为False。 139 | * 值为False时,连接自动关闭;为True时,触发ChannelInboundHandler的userEventTriggered()方法,事件为ChannelInputShutdownEvent。 140 | * @return boolean 141 | */ 142 | String childOptionAllowHalfClosure() default "false"; 143 | 144 | // ------------------------- idleEvent ------------------------- 145 | 146 | /** 147 | * 与IdleStateHandler中的readerIdleTimeSeconds一致,并且当它不为0时,将在pipeline中添加IdleStateHandler 148 | * @return int 149 | */ 150 | String readerIdleTimeSeconds() default "0"; 151 | 152 | /** 153 | * 与IdleStateHandler中的writerIdleTimeSeconds一致,并且当它不为0时,将在pipeline中添加IdleStateHandler 154 | * @return int 155 | */ 156 | String writerIdleTimeSeconds() default "0"; 157 | 158 | /** 159 | * 与IdleStateHandler中的allIdleTimeSeconds一致,并且当它不为0时,将在pipeline中添加IdleStateHandler 160 | * @return int 161 | */ 162 | String allIdleTimeSeconds() default "0"; 163 | 164 | // ------------------------- handshake ------------------------- 165 | 166 | /** 167 | * 最大允许帧载荷长度 168 | * @return int 169 | */ 170 | String maxFramePayloadLength() default "65536"; 171 | 172 | // ------------------------- eventExecutorGroup ------------------------- 173 | 174 | /** 175 | * 是否使用另一个线程池来执行耗时的同步业务逻辑 176 | * @return boolean 177 | */ 178 | String useEventExecutorGroup() default "true"; 179 | 180 | /** 181 | * eventExecutorGroup的线程数 182 | * @return int 183 | */ 184 | String eventExecutorGroupThreads() default "16"; 185 | 186 | // ------------------------- ssl (refer to spring Ssl) ------------------------- 187 | 188 | /** 189 | * {@link org.springframework.boot.web.server.Ssl} 190 | */ 191 | 192 | /** 193 | * 与spring-boot的server.ssl.key-password一致 194 | * @return String 195 | */ 196 | String sslKeyPassword() default ""; 197 | 198 | /** 199 | * 与spring-boot的server.ssl.key-store一致 200 | * @return String 201 | */ 202 | String sslKeyStore() default ""; 203 | 204 | /** 205 | * 与spring-boot的server.ssl.key-store-password一致 206 | * @return String 207 | */ 208 | String sslKeyStorePassword() default ""; 209 | 210 | /** 211 | * 与spring-boot的server.ssl.key-store-type一致 212 | * @return String 213 | */ 214 | String sslKeyStoreType() default ""; 215 | 216 | /** 217 | * 与spring-boot的server.ssl.trust-store一致 218 | * @return String 219 | */ 220 | String sslTrustStore() default ""; 221 | 222 | /** 223 | * 与spring-boot的server.ssl.trust-store-password一致 224 | * @return String 225 | */ 226 | String sslTrustStorePassword() default ""; 227 | 228 | /** 229 | * 与spring-boot的server.ssl.trust-store-type一致 230 | * @return String 231 | */ 232 | String sslTrustStoreType() default ""; 233 | 234 | // ------------------------- cors (refer to spring CrossOrigin) 235 | // ------------------------- 236 | 237 | /** 238 | * {@link org.springframework.web.bind.annotation.CrossOrigin} 239 | */ 240 | 241 | /** 242 | * 与spring boot的@CrossOrigin#origins一致 243 | * @return String[] 244 | */ 245 | String[] corsOrigins() default {}; 246 | 247 | /** 248 | * 与spring boot的@CrossOrigin#allowCredentials一致 249 | * @return String 250 | */ 251 | String corsAllowCredentials() default ""; 252 | 253 | } 254 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/domain/NettySession.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.domain; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.ByteBufAllocator; 5 | import io.netty.channel.*; 6 | import io.netty.channel.socket.DatagramChannel; 7 | import io.netty.channel.socket.DatagramPacket; 8 | import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; 9 | import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; 10 | import io.netty.util.AttributeKey; 11 | 12 | import java.net.InetSocketAddress; 13 | import java.net.SocketAddress; 14 | import java.nio.ByteBuffer; 15 | 16 | /** 17 | * @author twelvet 18 | */ 19 | public class NettySession { 20 | 21 | private final Channel channel; 22 | 23 | NettySession(Channel channel) { 24 | this.channel = channel; 25 | } 26 | 27 | /** 28 | * set subprotocols on {@link cn.twelvet.websocket.netty.annotation.BeforeHandshake} 29 | * @param subprotocols String 30 | */ 31 | public void setSubprotocols(String subprotocols) { 32 | setAttribute("subprotocols", subprotocols); 33 | } 34 | 35 | public ChannelFuture sendText(String message) { 36 | return channel.writeAndFlush(new TextWebSocketFrame(message)); 37 | } 38 | 39 | public ChannelFuture sendText(ByteBuf byteBuf) { 40 | return channel.writeAndFlush(new TextWebSocketFrame(byteBuf)); 41 | } 42 | 43 | public ChannelFuture sendText(ByteBuffer byteBuffer) { 44 | ByteBuf buffer = channel.alloc().buffer(byteBuffer.remaining()); 45 | buffer.writeBytes(byteBuffer); 46 | return channel.writeAndFlush(new TextWebSocketFrame(buffer)); 47 | } 48 | 49 | public ChannelFuture sendText(TextWebSocketFrame textWebSocketFrame) { 50 | return channel.writeAndFlush(textWebSocketFrame); 51 | } 52 | 53 | public ChannelFuture sendBinary(byte[] bytes) { 54 | ByteBuf buffer = channel.alloc().buffer(bytes.length); 55 | return channel.writeAndFlush(new BinaryWebSocketFrame(buffer.writeBytes(bytes))); 56 | } 57 | 58 | public ChannelFuture sendBinary(ByteBuf byteBuf) { 59 | return channel.writeAndFlush(new BinaryWebSocketFrame(byteBuf)); 60 | } 61 | 62 | public ChannelFuture sendBinary(ByteBuffer byteBuffer) { 63 | ByteBuf buffer = channel.alloc().buffer(byteBuffer.remaining()); 64 | buffer.writeBytes(byteBuffer); 65 | return channel.writeAndFlush(new BinaryWebSocketFrame(buffer)); 66 | } 67 | 68 | public ChannelFuture sendBinary(BinaryWebSocketFrame binaryWebSocketFrame) { 69 | return channel.writeAndFlush(binaryWebSocketFrame); 70 | } 71 | 72 | public void setAttribute(String name, T value) { 73 | AttributeKey sessionIdKey = AttributeKey.valueOf(name); 74 | channel.attr(sessionIdKey).set(value); 75 | } 76 | 77 | public T getAttribute(String name) { 78 | AttributeKey sessionIdKey = AttributeKey.valueOf(name); 79 | return channel.attr(sessionIdKey).get(); 80 | } 81 | 82 | public Channel channel() { 83 | return channel; 84 | } 85 | 86 | /** 87 | * Returns the globally unique identifier of this {@link Channel}. 88 | * @return ChannelId 89 | */ 90 | public ChannelId id() { 91 | return channel.id(); 92 | } 93 | 94 | /** 95 | * Returns the configuration of this channel. 96 | * @return ChannelConfig 97 | */ 98 | public ChannelConfig config() { 99 | return channel.config(); 100 | } 101 | 102 | /** 103 | * Returns {@code true} if the {@link Channel} is open and may get active later 104 | * @return boolean 105 | */ 106 | public boolean isOpen() { 107 | return channel.isOpen(); 108 | } 109 | 110 | /** 111 | * Returns {@code true} if the {@link Channel} is registered with an 112 | * {@link EventLoop}. 113 | * @return boolean 114 | */ 115 | public boolean isRegistered() { 116 | return channel.isRegistered(); 117 | } 118 | 119 | /** 120 | * Return {@code true} if the {@link Channel} is active and so connected. 121 | * @return boolean 122 | */ 123 | public boolean isActive() { 124 | return channel.isActive(); 125 | } 126 | 127 | /** 128 | * Return the {@link ChannelMetadata} of the {@link Channel} which describe the nature 129 | * of the {@link Channel}. 130 | * @return ChannelMetadata 131 | */ 132 | public ChannelMetadata metadata() { 133 | return channel.metadata(); 134 | } 135 | 136 | /** 137 | * Returns the local address where this channel is bound to. The returned 138 | * {@link SocketAddress} is supposed to be down-cast into more concrete type such as 139 | * {@link InetSocketAddress} to retrieve the detailed information. 140 | * @return the local address of this channel. {@code null} if this channel is not 141 | * bound. 142 | */ 143 | public SocketAddress localAddress() { 144 | return channel.localAddress(); 145 | } 146 | 147 | /** 148 | * Returns the remote address where this channel is connected to. The returned 149 | * {@link SocketAddress} is supposed to be down-cast into more concrete type such as 150 | * {@link InetSocketAddress} to retrieve the detailed information. 151 | * @return the remote address of this channel. {@code null} if this channel is not 152 | * connected. If this channel is not connected but it can receive messages from 153 | * arbitrary remote addresses (e.g. {@link DatagramChannel}, use 154 | * {@link DatagramPacket#recipient()} to determine the origination of the received 155 | * message as this method will return {@code null}. 156 | */ 157 | public SocketAddress remoteAddress() { 158 | return channel.remoteAddress(); 159 | } 160 | 161 | /** 162 | * Returns the {@link ChannelFuture} which will be notified when this channel is 163 | * closed. This method always returns the same future instance. 164 | * @return SocketAddress 165 | */ 166 | public ChannelFuture closeFuture() { 167 | return channel.closeFuture(); 168 | } 169 | 170 | /** 171 | * Returns {@code true} if and only if the I/O thread will perform the requested write 172 | * operation immediately. Any write requests made when this method returns 173 | * {@code false} are queued until the I/O thread is ready to process the queued write 174 | * requests. 175 | * @return boolean 176 | */ 177 | public boolean isWritable() { 178 | return channel.isWritable(); 179 | } 180 | 181 | /** 182 | * Get how many bytes can be written until {@link #isWritable()} returns 183 | * {@code false}. This quantity will always be non-negative. If {@link #isWritable()} 184 | * is {@code false} then 0. 185 | * @return long 186 | */ 187 | public long bytesBeforeUnwritable() { 188 | return channel.bytesBeforeUnwritable(); 189 | } 190 | 191 | /** 192 | * Get how many bytes must be drained from underlying buffers until 193 | * {@link #isWritable()} returns {@code true}. This quantity will always be 194 | * non-negative. If {@link #isWritable()} is {@code true} then 0. 195 | * @return long 196 | */ 197 | public long bytesBeforeWritable() { 198 | return channel.bytesBeforeWritable(); 199 | } 200 | 201 | /** 202 | * Returns an internal-use-only object that provides unsafe operations. 203 | * @return Channel.Unsafe 204 | */ 205 | public Channel.Unsafe unsafe() { 206 | return channel.unsafe(); 207 | } 208 | 209 | /** 210 | * Return the assigned {@link ChannelPipeline}. 211 | * @return ChannelPipeline 212 | */ 213 | public ChannelPipeline pipeline() { 214 | return channel.pipeline(); 215 | } 216 | 217 | /** 218 | * Return the assigned {@link ByteBufAllocator} which will be used to allocate 219 | * {@link ByteBuf}s. 220 | * @return ByteBufAllocator 221 | */ 222 | public ByteBufAllocator alloc() { 223 | return channel.alloc(); 224 | } 225 | 226 | public Channel read() { 227 | return channel.read(); 228 | } 229 | 230 | public Channel flush() { 231 | return channel.flush(); 232 | } 233 | 234 | public ChannelFuture close() { 235 | return channel.close(); 236 | } 237 | 238 | public ChannelFuture close(ChannelPromise promise) { 239 | return channel.close(promise); 240 | } 241 | 242 | } 243 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/standard/WebsocketServer.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.standard; 2 | 3 | import cn.twelvet.websocket.netty.domain.WebSocketEndpointServer; 4 | import cn.twelvet.websocket.netty.standard.handler.HttpServerHandler; 5 | import cn.twelvet.websocket.netty.util.SslUtils; 6 | import io.netty.bootstrap.ServerBootstrap; 7 | import io.netty.channel.*; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.nio.NioServerSocketChannel; 10 | import io.netty.channel.socket.nio.NioSocketChannel; 11 | import io.netty.handler.codec.http.HttpObjectAggregator; 12 | import io.netty.handler.codec.http.HttpServerCodec; 13 | import io.netty.handler.codec.http.cors.CorsConfig; 14 | import io.netty.handler.codec.http.cors.CorsConfigBuilder; 15 | import io.netty.handler.codec.http.cors.CorsHandler; 16 | import io.netty.handler.logging.LogLevel; 17 | import io.netty.handler.logging.LoggingHandler; 18 | import io.netty.handler.ssl.SslContext; 19 | import io.netty.util.concurrent.DefaultEventExecutorGroup; 20 | import io.netty.util.concurrent.EventExecutorGroup; 21 | import io.netty.util.internal.logging.InternalLogger; 22 | import io.netty.util.internal.logging.InternalLoggerFactory; 23 | import org.springframework.util.ObjectUtils; 24 | 25 | import javax.net.ssl.SSLException; 26 | import java.net.InetAddress; 27 | import java.net.InetSocketAddress; 28 | import java.net.UnknownHostException; 29 | 30 | /** 31 | * @author twelvet 32 | */ 33 | public class WebsocketServer { 34 | 35 | private final WebSocketEndpointServer webSocketEndpointServer; 36 | 37 | private final WebSocketEndpointConfig webSocketEndpointConfig; 38 | 39 | private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebsocketServer.class); 40 | 41 | public WebsocketServer(WebSocketEndpointServer webSocketServerHandler, 42 | WebSocketEndpointConfig webSocketEndpointConfig) { 43 | this.webSocketEndpointServer = webSocketServerHandler; 44 | this.webSocketEndpointConfig = webSocketEndpointConfig; 45 | 46 | } 47 | 48 | /** 49 | * Start Netty 50 | * @throws InterruptedException InterruptedException 51 | * @throws SSLException SSLException 52 | */ 53 | public void init() throws InterruptedException, SSLException { 54 | EventExecutorGroup eventExecutorGroup = null; 55 | final SslContext sslCtx; 56 | // SSL 57 | if (!ObjectUtils.isEmpty(webSocketEndpointConfig.getKeyStore())) { 58 | sslCtx = SslUtils.createSslContext(webSocketEndpointConfig.getKeyPassword(), 59 | webSocketEndpointConfig.getKeyStore(), webSocketEndpointConfig.getKeyStoreType(), 60 | webSocketEndpointConfig.getKeyStorePassword(), webSocketEndpointConfig.getTrustStore(), 61 | webSocketEndpointConfig.getTrustStoreType(), webSocketEndpointConfig.getTrustStorePassword()); 62 | } 63 | else { 64 | sslCtx = null; 65 | } 66 | 67 | final CorsConfig corsConfig = createCorsConfig(webSocketEndpointConfig.getCorsOrigins(), 68 | webSocketEndpointConfig.getCorsAllowCredentials()); 69 | 70 | if (webSocketEndpointConfig.isUseEventExecutorGroup()) { 71 | eventExecutorGroup = new DefaultEventExecutorGroup( 72 | webSocketEndpointConfig.getEventExecutorGroupThreads() == 0 ? 16 73 | : webSocketEndpointConfig.getEventExecutorGroupThreads()); 74 | } 75 | 76 | EventLoopGroup bossGroup = new NioEventLoopGroup(webSocketEndpointConfig.getBossLoopGroupThreads()); 77 | EventLoopGroup workerGroup = new NioEventLoopGroup(webSocketEndpointConfig.getWorkerLoopGroupThreads()); 78 | 79 | ServerBootstrap bootstrap = new ServerBootstrap(); 80 | EventExecutorGroup finalEventExecutorGroup = eventExecutorGroup; 81 | 82 | bootstrap.group(bossGroup, workerGroup) 83 | .channel(NioServerSocketChannel.class) 84 | // ConnectTimeoutMillis 85 | .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, webSocketEndpointConfig.getConnectTimeoutMillis()) 86 | // Waiting queue 87 | .option(ChannelOption.SO_BACKLOG, webSocketEndpointConfig.getSoBacklog()) 88 | .childOption(ChannelOption.WRITE_SPIN_COUNT, webSocketEndpointConfig.getWriteSpinCount()) 89 | .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, 90 | new WriteBufferWaterMark(webSocketEndpointConfig.getWriteBufferLowWaterMark(), 91 | webSocketEndpointConfig.getWriteBufferHighWaterMark())) 92 | .childOption(ChannelOption.TCP_NODELAY, webSocketEndpointConfig.isTcpNodelay()) 93 | .childOption(ChannelOption.SO_KEEPALIVE, webSocketEndpointConfig.isSoKeepalive()) 94 | .childOption(ChannelOption.SO_LINGER, webSocketEndpointConfig.getSoLinger()) 95 | .childOption(ChannelOption.ALLOW_HALF_CLOSURE, webSocketEndpointConfig.isAllowHalfClosure()) 96 | .handler(new LoggingHandler(LogLevel.DEBUG)) 97 | .childHandler(new ChannelInitializer() { 98 | @Override 99 | protected void initChannel(NioSocketChannel ch) { 100 | ChannelPipeline pipeline = ch.pipeline(); 101 | if (sslCtx != null) { 102 | pipeline.addFirst(sslCtx.newHandler(ch.alloc())); 103 | } 104 | 105 | // http解码器 106 | pipeline.addLast(new HttpServerCodec()); 107 | // http聚合器 108 | pipeline.addLast(new HttpObjectAggregator(65536)); 109 | 110 | if (corsConfig != null) { 111 | pipeline.addLast(new CorsHandler(corsConfig)); 112 | } 113 | 114 | pipeline.addLast(new HttpServerHandler(webSocketEndpointServer, webSocketEndpointConfig, 115 | finalEventExecutorGroup, corsConfig != null)); 116 | } 117 | }); 118 | 119 | if (webSocketEndpointConfig.getSoRcvbuf() != -1) { 120 | bootstrap.childOption(ChannelOption.SO_RCVBUF, webSocketEndpointConfig.getSoRcvbuf()); 121 | } 122 | 123 | if (webSocketEndpointConfig.getSoSndbuf() != -1) { 124 | bootstrap.childOption(ChannelOption.SO_SNDBUF, webSocketEndpointConfig.getSoSndbuf()); 125 | } 126 | 127 | ChannelFuture channelFuture; 128 | if ("0.0.0.0".equals(webSocketEndpointConfig.getHost())) { 129 | channelFuture = bootstrap.bind(webSocketEndpointConfig.getPort()); 130 | } 131 | else { 132 | try { 133 | channelFuture = bootstrap.bind(new InetSocketAddress( 134 | InetAddress.getByName(webSocketEndpointConfig.getHost()), webSocketEndpointConfig.getPort())); 135 | } 136 | catch (UnknownHostException e) { 137 | channelFuture = bootstrap.bind(webSocketEndpointConfig.getHost(), webSocketEndpointConfig.getPort()); 138 | e.printStackTrace(); 139 | } 140 | } 141 | 142 | channelFuture.addListener(future -> { 143 | if (!future.isSuccess()) { 144 | future.cause().printStackTrace(); 145 | } 146 | }); 147 | 148 | Runtime.getRuntime().addShutdownHook(new Thread(() -> { 149 | bossGroup.shutdownGracefully().syncUninterruptibly(); 150 | workerGroup.shutdownGracefully().syncUninterruptibly(); 151 | })); 152 | } 153 | 154 | /** 155 | * Cross Configuration 156 | * @param corsOrigins address 157 | * @param corsAllowCredentials Whether credentials exist 158 | * @return CorsConfig 159 | */ 160 | private CorsConfig createCorsConfig(String[] corsOrigins, Boolean corsAllowCredentials) { 161 | if (corsOrigins.length == 0) { 162 | return null; 163 | } 164 | CorsConfigBuilder corsConfigBuilder = null; 165 | 166 | for (String corsOrigin : corsOrigins) { 167 | if ("*".equals(corsOrigin)) { 168 | // any 169 | corsConfigBuilder = CorsConfigBuilder.forAnyOrigin(); 170 | break; 171 | } 172 | } 173 | 174 | if (corsConfigBuilder == null) { 175 | corsConfigBuilder = CorsConfigBuilder.forOrigins(corsOrigins); 176 | } 177 | 178 | // Whether to send cookies 179 | if (corsAllowCredentials != null && corsAllowCredentials) { 180 | corsConfigBuilder.allowCredentials(); 181 | } 182 | 183 | corsConfigBuilder.allowNullOrigin(); 184 | return corsConfigBuilder.build(); 185 | } 186 | 187 | /** 188 | * Access to services 189 | * @return WebSocketEndpointServer 190 | */ 191 | public WebSocketEndpointServer getEndpointServer() { 192 | return webSocketEndpointServer; 193 | } 194 | 195 | } 196 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/domain/WebSocketEndpointServer.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.domain; 2 | 3 | import cn.twelvet.websocket.netty.support.impl.path.AntPathMatcherWrapper; 4 | import cn.twelvet.websocket.netty.support.impl.path.DefaultPathMatcher; 5 | import cn.twelvet.websocket.netty.support.impl.PathVariableMapMethodArgumentResolver; 6 | import cn.twelvet.websocket.netty.support.impl.PathVariableMethodArgumentResolver; 7 | import io.netty.channel.Channel; 8 | import io.netty.handler.codec.http.FullHttpRequest; 9 | import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; 10 | import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; 11 | import io.netty.handler.codec.http.websocketx.WebSocketFrame; 12 | import io.netty.util.Attribute; 13 | import io.netty.util.AttributeKey; 14 | import io.netty.util.internal.logging.InternalLogger; 15 | import io.netty.util.internal.logging.InternalLoggerFactory; 16 | import org.springframework.beans.TypeMismatchException; 17 | import cn.twelvet.websocket.netty.standard.WebSocketEndpointConfig; 18 | import cn.twelvet.websocket.netty.support.*; 19 | 20 | import java.lang.reflect.Method; 21 | import java.util.*; 22 | 23 | /** 24 | * @author twelvet Event handling service 25 | */ 26 | public class WebSocketEndpointServer { 27 | 28 | private static final AttributeKey WEB_SOCKET_KEY = AttributeKey.valueOf("WEBSOCKET_IMPLEMENT"); 29 | 30 | public static final AttributeKey SESSION_KEY = AttributeKey.valueOf("WEBSOCKET_SESSION"); 31 | 32 | private static final AttributeKey PATH_KEY = AttributeKey.valueOf("WEBSOCKET_PATH"); 33 | 34 | public static final AttributeKey> URI_TEMPLATE = AttributeKey.valueOf("WEBSOCKET_URI_TEMPLATE"); 35 | 36 | public static final AttributeKey>> REQUEST_PARAM = AttributeKey 37 | .valueOf("WEBSOCKET_REQUEST_PARAM"); 38 | 39 | private final Map pathMethodMappingMap = new HashMap<>(); 40 | 41 | private final WebSocketEndpointConfig config; 42 | 43 | private final Set pathMatchers = new HashSet<>(); 44 | 45 | private static final InternalLogger log = InternalLoggerFactory.getInstance(WebSocketEndpointServer.class); 46 | 47 | public WebSocketEndpointServer(WebSocketMethodMapping methodMapping, WebSocketEndpointConfig config, String path) { 48 | addPathMethodMapping(path, methodMapping); 49 | this.config = config; 50 | } 51 | 52 | public boolean hasBeforeHandshake(Channel channel, String path) { 53 | WebSocketMethodMapping methodMapping = getWebSocketMethodMapping(path, channel); 54 | return methodMapping.getBeforeHandshake() != null; 55 | } 56 | 57 | public void doBeforeHandshake(Channel channel, FullHttpRequest req, String path) { 58 | WebSocketMethodMapping methodMapping = getWebSocketMethodMapping(path, channel); 59 | 60 | Object implement = null; 61 | try { 62 | implement = methodMapping.getEndpointInstance(); 63 | } 64 | catch (Exception e) { 65 | log.error(e); 66 | return; 67 | } 68 | channel.attr(WEB_SOCKET_KEY).set(implement); 69 | NettySession nettySession = new NettySession(channel); 70 | channel.attr(SESSION_KEY).set(nettySession); 71 | Method beforeHandshake = methodMapping.getBeforeHandshake(); 72 | if (beforeHandshake != null) { 73 | try { 74 | beforeHandshake.invoke(implement, methodMapping.getBeforeHandshakeArgs(channel, req)); 75 | } 76 | catch (TypeMismatchException e) { 77 | throw e; 78 | } 79 | catch (Throwable t) { 80 | log.error(t); 81 | } 82 | } 83 | } 84 | 85 | public void doOnOpen(Channel channel, FullHttpRequest req, String path) { 86 | WebSocketMethodMapping methodMapping = getWebSocketMethodMapping(path, channel); 87 | 88 | Object implement = channel.attr(WEB_SOCKET_KEY).get(); 89 | if (implement == null) { 90 | try { 91 | implement = methodMapping.getEndpointInstance(); 92 | channel.attr(WEB_SOCKET_KEY).set(implement); 93 | } 94 | catch (Exception e) { 95 | log.error(e); 96 | return; 97 | } 98 | NettySession nettySession = new NettySession(channel); 99 | channel.attr(SESSION_KEY).set(nettySession); 100 | } 101 | 102 | Method onOpenMethod = methodMapping.getOnOpen(); 103 | if (onOpenMethod != null) { 104 | try { 105 | onOpenMethod.invoke(implement, methodMapping.getOnOpenArgs(channel, req)); 106 | } 107 | catch (TypeMismatchException e) { 108 | throw e; 109 | } 110 | catch (Throwable t) { 111 | log.error(t); 112 | } 113 | } 114 | } 115 | 116 | public void doOnClose(Channel channel) { 117 | Attribute attrPath = channel.attr(PATH_KEY); 118 | WebSocketMethodMapping methodMapping = null; 119 | if (pathMethodMappingMap.size() == 1) { 120 | methodMapping = pathMethodMappingMap.values().iterator().next(); 121 | } 122 | else { 123 | String path = attrPath.get(); 124 | methodMapping = pathMethodMappingMap.get(path); 125 | if (methodMapping == null) { 126 | return; 127 | } 128 | } 129 | if (methodMapping.getOnClose() != null) { 130 | if (!channel.hasAttr(SESSION_KEY)) { 131 | return; 132 | } 133 | Object implement = channel.attr(WEB_SOCKET_KEY).get(); 134 | try { 135 | methodMapping.getOnClose().invoke(implement, methodMapping.getOnCloseArgs(channel)); 136 | } 137 | catch (Throwable t) { 138 | log.error(t); 139 | } 140 | } 141 | } 142 | 143 | public void doOnError(Channel channel, Throwable throwable) { 144 | WebSocketMethodMapping webSocketMethodMapping = getWebSocketMethodMapping(channel); 145 | if (webSocketMethodMapping.getOnError() != null) { 146 | if (!channel.hasAttr(SESSION_KEY)) { 147 | return; 148 | } 149 | Object implement = channel.attr(WEB_SOCKET_KEY).get(); 150 | try { 151 | Method method = webSocketMethodMapping.getOnError(); 152 | Object[] args = webSocketMethodMapping.getOnErrorArgs(channel, throwable); 153 | method.invoke(implement, args); 154 | } 155 | catch (Throwable t) { 156 | log.error(t); 157 | } 158 | } 159 | } 160 | 161 | public void doOnMessage(Channel channel, WebSocketFrame frame) { 162 | WebSocketMethodMapping webSocketMethodMapping = getWebSocketMethodMapping(channel); 163 | if (webSocketMethodMapping.getOnMessage() != null) { 164 | TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; 165 | Object implement = channel.attr(WEB_SOCKET_KEY).get(); 166 | try { 167 | webSocketMethodMapping.getOnMessage() 168 | .invoke(implement, webSocketMethodMapping.getOnMessageArgs(channel, textFrame)); 169 | } 170 | catch (Throwable t) { 171 | log.error(t); 172 | } 173 | } 174 | } 175 | 176 | public void doOnBinary(Channel channel, WebSocketFrame frame) { 177 | WebSocketMethodMapping webSocketMethodMapping = getWebSocketMethodMapping(channel); 178 | if (webSocketMethodMapping.getOnBinary() != null) { 179 | BinaryWebSocketFrame binaryWebSocketFrame = (BinaryWebSocketFrame) frame; 180 | Object implement = channel.attr(WEB_SOCKET_KEY).get(); 181 | try { 182 | webSocketMethodMapping.getOnBinary() 183 | .invoke(implement, webSocketMethodMapping.getOnBinaryArgs(channel, binaryWebSocketFrame)); 184 | } 185 | catch (Throwable t) { 186 | log.error(t); 187 | } 188 | } 189 | } 190 | 191 | public void doOnEvent(Channel channel, Object evt) { 192 | WebSocketMethodMapping webSocketMethodMapping = getWebSocketMethodMapping(channel); 193 | if (webSocketMethodMapping.getOnEvent() != null) { 194 | if (!channel.hasAttr(SESSION_KEY)) { 195 | return; 196 | } 197 | Object implement = channel.attr(WEB_SOCKET_KEY).get(); 198 | try { 199 | webSocketMethodMapping.getOnEvent() 200 | .invoke(implement, webSocketMethodMapping.getOnEventArgs(channel, evt)); 201 | } 202 | catch (Throwable t) { 203 | log.error(t); 204 | } 205 | } 206 | } 207 | 208 | public String getHost() { 209 | return config.getHost(); 210 | } 211 | 212 | public int getPort() { 213 | return config.getPort(); 214 | } 215 | 216 | public Set getPathMatcherSet() { 217 | return pathMatchers; 218 | } 219 | 220 | public void addPathMethodMapping(String path, WebSocketMethodMapping webSocketMethodMapping) { 221 | pathMethodMappingMap.put(path, webSocketMethodMapping); 222 | for (MethodArgumentResolver onOpenArgResolver : webSocketMethodMapping.getOnOpenArgResolvers()) { 223 | if (onOpenArgResolver instanceof PathVariableMethodArgumentResolver 224 | || onOpenArgResolver instanceof PathVariableMapMethodArgumentResolver) { 225 | pathMatchers.add(new AntPathMatcherWrapper(path)); 226 | return; 227 | } 228 | } 229 | pathMatchers.add(new DefaultPathMatcher(path)); 230 | } 231 | 232 | private WebSocketMethodMapping getWebSocketMethodMapping(Channel channel) { 233 | Attribute attrPath = channel.attr(PATH_KEY); 234 | if (pathMethodMappingMap.size() == 1) { 235 | return pathMethodMappingMap.values().iterator().next(); 236 | } 237 | else { 238 | String path = attrPath.get(); 239 | return pathMethodMappingMap.get(path); 240 | } 241 | } 242 | 243 | private WebSocketMethodMapping getWebSocketMethodMapping(String path, Channel channel) { 244 | WebSocketMethodMapping methodMapping; 245 | if (pathMethodMappingMap.size() == 1) { 246 | methodMapping = pathMethodMappingMap.values().iterator().next(); 247 | } 248 | else { 249 | Attribute attrPath = channel.attr(PATH_KEY); 250 | attrPath.set(path); 251 | methodMapping = pathMethodMappingMap.get(path); 252 | if (methodMapping == null) { 253 | throw new RuntimeException("path " + path + " is not in pathMethodMappingMap "); 254 | } 255 | } 256 | return methodMapping; 257 | } 258 | 259 | } 260 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/standard/WebSocketEndpointConfig.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.standard; 2 | 3 | import org.springframework.util.ObjectUtils; 4 | 5 | import java.io.IOException; 6 | import java.net.InetSocketAddress; 7 | import java.net.Socket; 8 | 9 | /** 10 | * @author twelvet WebSocket配置获取 11 | */ 12 | public class WebSocketEndpointConfig { 13 | 14 | /** 15 | * 绑定地址 16 | */ 17 | private final String host; 18 | 19 | /** 20 | * 端口 21 | */ 22 | private final int port; 23 | 24 | /** 25 | * bossEventLoopGroup的线程数 26 | */ 27 | private final int bossLoopGroupThreads; 28 | 29 | /** 30 | * workerEventLoopGroup的线程数 31 | */ 32 | private final int workerLoopGroupThreads; 33 | 34 | /** 35 | * 是否添加WebSocketServerCompressionHandler到pipeline 36 | */ 37 | private final boolean useCompressionHandler; 38 | 39 | /** 40 | * 连接超时毫秒数 41 | */ 42 | private final int connectTimeoutMillis; 43 | 44 | /** 45 | * 服务端接受连接的队列长度,如果队列已满,客户端连接将被拒绝 46 | */ 47 | private final int soBacklog; 48 | 49 | /** 50 | * 一个Loop写操作执行的最大次数,默认值为16。 51 | * 也就是说,对于大数据量的写操作至多进行16次,如果16次仍没有全部写完数据,此时会提交一个新的写任务给EventLoop,任务将在下次调度继续执行。 52 | * 这样,其他的写请求才能被响应不会因为单个大数据量写请求而耽误 53 | */ 54 | private final int writeSpinCount; 55 | 56 | /** 57 | * 写高水位标记,默认值64KB。如果Netty的写缓冲区中的字节超过该值,Channel的isWritable()返回False 58 | */ 59 | private final int writeBufferHighWaterMark; 60 | 61 | /** 62 | * 写低水位标记,默认值32KB。 当Netty的写缓冲区中的字节超过高水位之后若下降到低水位,则Channel的isWritable()返回True。 63 | * 写高低水位标记使用户可以控制写入数据速度,从而实现流量控制。 64 | * 推荐做法是:每次调用channel.write(msg)方法首先调用channel.isWritable()判断是否可写。 65 | */ 66 | private final int writeBufferLowWaterMark; 67 | 68 | /** 69 | * TCP数据接收缓冲区大小。 该缓冲区即TCP接收滑动窗口,linux操作系统可使用命令:cat /proc/sys/net/ipv4/tcp_rmem查询其大小。 70 | * 一般情况下,该值可由用户在任意时刻设置,但当设置值超过64KB时,需要在连接到远端之前设置。 71 | */ 72 | private final int soRcvbuf; 73 | 74 | /** 75 | * TCP数据发送缓冲区大小。 该缓冲区即TCP发送滑动窗口,linux操作系统可使用命令:cat /proc/sys/net/ipv4/tcp_smem查询其大小 76 | */ 77 | private final int soSndbuf; 78 | 79 | /** 80 | * 立即发送数据,默认值为Ture(Netty默认为True而操作系统默认为False)。 81 | * 该值设置Nagle算法的启用,改算法将小的碎片数据连接成更大的报文来最小化所发送的报文的数量,如果需要发送一些较小的报文,则需要禁用该算法。 82 | * Netty默认禁用该算法,从而最小化报文传输延时 83 | */ 84 | private final boolean tcpNodelay; 85 | 86 | /** 87 | * 连接保活,默认值为False。 启用该功能时,TCP会主动探测空闲连接的有效性。 88 | * 可以将此功能视为TCP的心跳机制,需要注意的是:默认的心跳间隔是7200s即2小时。Netty默认关闭该功能。 89 | */ 90 | private final boolean soKeepalive; 91 | 92 | /** 93 | * 关闭Socket的延迟时间,默认值为-1,表示禁用该功能。 -1表示socket.close()方法立即返回,但OS底层会将发送缓冲区全部发送到对端。 94 | * 0表示socket.close()方法立即返回,OS放弃发送缓冲区的数据直接向对端发送RST包,对端收到复位错误。 95 | * 非0整数值表示调用socket.close()方法的线程被阻塞直到延迟时间到或发送缓冲区中的数据发送完毕,若超时,则对端会收到复位错误。 96 | */ 97 | private final int soLinger; 98 | 99 | /** 100 | * 一个连接的远端关闭时本地端是否关闭,默认值为False。 101 | * 值为False时,连接自动关闭;为True时,触发ChannelInboundHandler的userEventTriggered()方法,事件为ChannelInputShutdownEvent。 102 | */ 103 | private final boolean allowHalfClosure; 104 | 105 | // ------------------------- idleEvent ------------------------- 106 | 107 | /** 108 | * 与IdleStateHandler中的readerIdleTimeSeconds一致,并且当它不为0时,将在pipeline中添加IdleStateHandler 109 | */ 110 | private final int readerIdleTimeSeconds; 111 | 112 | /** 113 | * 与IdleStateHandler中的writerIdleTimeSeconds一致,并且当它不为0时,将在pipeline中添加IdleStateHandler 114 | */ 115 | private final int writerIdleTimeSeconds; 116 | 117 | /** 118 | * 与IdleStateHandler中的allIdleTimeSeconds一致,并且当它不为0时,将在pipeline中添加IdleStateHandler 119 | */ 120 | private final int allIdleTimeSeconds; 121 | 122 | /** 123 | * 最大允许帧载荷长度 124 | */ 125 | private final int maxFramePayloadLength; 126 | 127 | /** 128 | * 是否使用另一个线程池来执行耗时的同步业务逻辑 129 | */ 130 | private final boolean useEventExecutorGroup; 131 | 132 | /** 133 | * eventExecutorGroup的线程数 134 | */ 135 | private final int eventExecutorGroupThreads; 136 | 137 | /*************************************************** 138 | * SSL 139 | *******************************************************************/ 140 | /** 141 | * 与spring-boot的server.ssl.key-password一致 142 | */ 143 | private final String keyPassword; 144 | 145 | /** 146 | * 与spring-boot的server.ssl.key-store一致 147 | */ 148 | private final String keyStore; 149 | 150 | /** 151 | * 与spring-boot的server.ssl.key-store-password一致 152 | */ 153 | private final String keyStorePassword; 154 | 155 | /** 156 | * 与spring-boot的server.ssl.key-store-type一致 157 | */ 158 | private final String keyStoreType; 159 | 160 | /** 161 | * 与spring-boot的server.ssl.trust-store一致 162 | */ 163 | private final String trustStore; 164 | 165 | /** 166 | * 与spring-boot的server.ssl.trust-store-password一致 167 | */ 168 | private final String trustStorePassword; 169 | 170 | /** 171 | * 与spring-boot的server.ssl.trust-store-type一致 172 | */ 173 | private final String trustStoreType; 174 | 175 | /*************************************************** 176 | * 跨域 177 | *******************************************************************/ 178 | /** 179 | * 与spring-boot的@CrossOrigin#origins一致 180 | */ 181 | private final String[] corsOrigins; 182 | 183 | /** 184 | * 与spring-boot的@CrossOrigin#allowCredentials一致 185 | */ 186 | private final Boolean corsAllowCredentials; 187 | 188 | /** 189 | * 随机端口 190 | */ 191 | private static Integer randomPort; 192 | 193 | public WebSocketEndpointConfig(String host, int port, int bossLoopGroupThreads, int workerLoopGroupThreads, 194 | boolean useCompressionHandler, int connectTimeoutMillis, int soBacklog, int writeSpinCount, 195 | int writeBufferHighWaterMark, int writeBufferLowWaterMark, int soRcvbuf, int soSndbuf, boolean tcpNodelay, 196 | boolean soKeepalive, int soLinger, boolean allowHalfClosure, int readerIdleTimeSeconds, 197 | int writerIdleTimeSeconds, int allIdleTimeSeconds, int maxFramePayloadLength, boolean useEventExecutorGroup, 198 | int eventExecutorGroupThreads, String keyPassword, String keyStore, String keyStorePassword, 199 | String keyStoreType, String trustStore, String trustStorePassword, String trustStoreType, 200 | String[] corsOrigins, Boolean corsAllowCredentials) { 201 | if (ObjectUtils.isEmpty(host) || "0.0.0.0".equals(host) || "0.0.0.0/0.0.0.0".equals(host)) { 202 | this.host = "0.0.0.0"; 203 | } 204 | else { 205 | this.host = host; 206 | } 207 | this.port = getAvailablePort(port); 208 | this.bossLoopGroupThreads = bossLoopGroupThreads; 209 | this.workerLoopGroupThreads = workerLoopGroupThreads; 210 | this.useCompressionHandler = useCompressionHandler; 211 | this.connectTimeoutMillis = connectTimeoutMillis; 212 | this.soBacklog = soBacklog; 213 | this.writeSpinCount = writeSpinCount; 214 | this.writeBufferHighWaterMark = writeBufferHighWaterMark; 215 | this.writeBufferLowWaterMark = writeBufferLowWaterMark; 216 | this.soRcvbuf = soRcvbuf; 217 | this.soSndbuf = soSndbuf; 218 | this.tcpNodelay = tcpNodelay; 219 | this.soKeepalive = soKeepalive; 220 | this.soLinger = soLinger; 221 | this.allowHalfClosure = allowHalfClosure; 222 | this.readerIdleTimeSeconds = readerIdleTimeSeconds; 223 | this.writerIdleTimeSeconds = writerIdleTimeSeconds; 224 | this.allIdleTimeSeconds = allIdleTimeSeconds; 225 | this.maxFramePayloadLength = maxFramePayloadLength; 226 | this.useEventExecutorGroup = useEventExecutorGroup; 227 | this.eventExecutorGroupThreads = eventExecutorGroupThreads; 228 | 229 | this.keyPassword = keyPassword; 230 | this.keyStore = keyStore; 231 | this.keyStorePassword = keyStorePassword; 232 | this.keyStoreType = keyStoreType; 233 | this.trustStore = trustStore; 234 | this.trustStorePassword = trustStorePassword; 235 | this.trustStoreType = trustStoreType; 236 | 237 | this.corsOrigins = corsOrigins; 238 | this.corsAllowCredentials = corsAllowCredentials; 239 | } 240 | 241 | /** 242 | * Get port or random port 243 | * @param port port 244 | * @return port 245 | */ 246 | private int getAvailablePort(int port) { 247 | if (port != 0) { 248 | return port; 249 | } 250 | if (randomPort != null && randomPort != 0) { 251 | return randomPort; 252 | } 253 | InetSocketAddress inetSocketAddress = new InetSocketAddress(0); 254 | Socket socket = new Socket(); 255 | try { 256 | socket.bind(inetSocketAddress); 257 | } 258 | catch (IOException e) { 259 | e.printStackTrace(); 260 | } 261 | int localPort = socket.getLocalPort(); 262 | try { 263 | socket.close(); 264 | } 265 | catch (IOException e) { 266 | e.printStackTrace(); 267 | } 268 | randomPort = localPort; 269 | return localPort; 270 | } 271 | 272 | public String getHost() { 273 | return host; 274 | } 275 | 276 | public int getPort() { 277 | return port; 278 | } 279 | 280 | public int getBossLoopGroupThreads() { 281 | return bossLoopGroupThreads; 282 | } 283 | 284 | public int getWorkerLoopGroupThreads() { 285 | return workerLoopGroupThreads; 286 | } 287 | 288 | public boolean isUseCompressionHandler() { 289 | return useCompressionHandler; 290 | } 291 | 292 | public int getConnectTimeoutMillis() { 293 | return connectTimeoutMillis; 294 | } 295 | 296 | public int getSoBacklog() { 297 | return soBacklog; 298 | } 299 | 300 | public int getWriteSpinCount() { 301 | return writeSpinCount; 302 | } 303 | 304 | public int getWriteBufferHighWaterMark() { 305 | return writeBufferHighWaterMark; 306 | } 307 | 308 | public int getWriteBufferLowWaterMark() { 309 | return writeBufferLowWaterMark; 310 | } 311 | 312 | public int getSoRcvbuf() { 313 | return soRcvbuf; 314 | } 315 | 316 | public int getSoSndbuf() { 317 | return soSndbuf; 318 | } 319 | 320 | public boolean isTcpNodelay() { 321 | return tcpNodelay; 322 | } 323 | 324 | public boolean isSoKeepalive() { 325 | return soKeepalive; 326 | } 327 | 328 | public int getSoLinger() { 329 | return soLinger; 330 | } 331 | 332 | public boolean isAllowHalfClosure() { 333 | return allowHalfClosure; 334 | } 335 | 336 | public static Integer getRandomPort() { 337 | return randomPort; 338 | } 339 | 340 | public int getReaderIdleTimeSeconds() { 341 | return readerIdleTimeSeconds; 342 | } 343 | 344 | public int getWriterIdleTimeSeconds() { 345 | return writerIdleTimeSeconds; 346 | } 347 | 348 | public int getAllIdleTimeSeconds() { 349 | return allIdleTimeSeconds; 350 | } 351 | 352 | public int getMaxFramePayloadLength() { 353 | return maxFramePayloadLength; 354 | } 355 | 356 | public boolean isUseEventExecutorGroup() { 357 | return useEventExecutorGroup; 358 | } 359 | 360 | public int getEventExecutorGroupThreads() { 361 | return eventExecutorGroupThreads; 362 | } 363 | 364 | public String getKeyPassword() { 365 | return keyPassword; 366 | } 367 | 368 | public String getKeyStore() { 369 | return keyStore; 370 | } 371 | 372 | public String getKeyStorePassword() { 373 | return keyStorePassword; 374 | } 375 | 376 | public String getKeyStoreType() { 377 | return keyStoreType; 378 | } 379 | 380 | public String getTrustStore() { 381 | return trustStore; 382 | } 383 | 384 | public String getTrustStorePassword() { 385 | return trustStorePassword; 386 | } 387 | 388 | public String getTrustStoreType() { 389 | return trustStoreType; 390 | } 391 | 392 | public String[] getCorsOrigins() { 393 | return corsOrigins; 394 | } 395 | 396 | public Boolean getCorsAllowCredentials() { 397 | return corsAllowCredentials; 398 | } 399 | 400 | } 401 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright (c) 2020 twelvet Authors. All Rights Reserved. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/standard/handler/HttpServerHandler.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.standard.handler; 2 | 3 | import cn.twelvet.websocket.netty.standard.WebSocketEndpointConfig; 4 | import io.netty.buffer.ByteBuf; 5 | import io.netty.buffer.ByteBufAllocator; 6 | import io.netty.buffer.Unpooled; 7 | import io.netty.channel.*; 8 | import io.netty.handler.codec.http.*; 9 | import io.netty.handler.codec.http.cors.CorsHandler; 10 | import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; 11 | import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator; 12 | import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker; 13 | import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory; 14 | import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler; 15 | import io.netty.handler.timeout.IdleStateHandler; 16 | import io.netty.util.AttributeKey; 17 | import io.netty.util.CharsetUtil; 18 | import io.netty.util.concurrent.EventExecutorGroup; 19 | import io.netty.util.internal.logging.InternalLogger; 20 | import io.netty.util.internal.logging.InternalLoggerFactory; 21 | import org.springframework.beans.TypeMismatchException; 22 | import org.springframework.util.ObjectUtils; 23 | import cn.twelvet.websocket.netty.domain.WebSocketEndpointServer; 24 | import cn.twelvet.websocket.netty.support.WsPathMatcher; 25 | 26 | import java.io.InputStream; 27 | import java.util.Set; 28 | 29 | import static io.netty.handler.codec.http.HttpHeaderNames.*; 30 | import static io.netty.handler.codec.http.HttpMethod.GET; 31 | import static io.netty.handler.codec.http.HttpResponseStatus.*; 32 | import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; 33 | 34 | /** 35 | * @author twelvet Process request information 36 | */ 37 | public class HttpServerHandler extends SimpleChannelInboundHandler { 38 | 39 | private static final InternalLogger log = InternalLoggerFactory.getInstance(HttpServerHandler.class); 40 | 41 | private final WebSocketEndpointServer webSocketEndpointServer; 42 | 43 | private final WebSocketEndpointConfig webSocketEndpointConfig; 44 | 45 | private final EventExecutorGroup eventExecutorGroup; 46 | 47 | private final boolean isCors; 48 | 49 | private static ByteBuf faviconByteBuf = null; 50 | 51 | private static ByteBuf notFoundByteBuf = null; 52 | 53 | private static ByteBuf badRequestByteBuf = null; 54 | 55 | private static ByteBuf forbiddenByteBuf = null; 56 | 57 | private static ByteBuf internalServerErrorByteBuf = null; 58 | 59 | static { 60 | faviconByteBuf = buildStaticRes("/favicon.ico"); 61 | notFoundByteBuf = buildStaticRes("/public/error/404.html"); 62 | badRequestByteBuf = buildStaticRes("/public/error/400.html"); 63 | forbiddenByteBuf = buildStaticRes("/public/error/403.html"); 64 | internalServerErrorByteBuf = buildStaticRes("/public/error/500.html"); 65 | if (notFoundByteBuf == null) { 66 | notFoundByteBuf = buildStaticRes("/public/error/4xx.html"); 67 | } 68 | if (badRequestByteBuf == null) { 69 | badRequestByteBuf = buildStaticRes("/public/error/4xx.html"); 70 | } 71 | if (forbiddenByteBuf == null) { 72 | forbiddenByteBuf = buildStaticRes("/public/error/4xx.html"); 73 | } 74 | if (internalServerErrorByteBuf == null) { 75 | internalServerErrorByteBuf = buildStaticRes("/public/error/5xx.html"); 76 | } 77 | } 78 | 79 | private static ByteBuf buildStaticRes(String resPath) { 80 | try { 81 | InputStream inputStream = HttpServerHandler.class.getResourceAsStream(resPath); 82 | if (inputStream != null) { 83 | int available = inputStream.available(); 84 | if (available != 0) { 85 | byte[] bytes = new byte[available]; 86 | inputStream.read(bytes); 87 | return ByteBufAllocator.DEFAULT.buffer(bytes.length).writeBytes(bytes); 88 | } 89 | } 90 | } 91 | catch (Exception e) { 92 | } 93 | return null; 94 | } 95 | 96 | public HttpServerHandler(WebSocketEndpointServer webSocketEndpointServer, 97 | WebSocketEndpointConfig webSocketEndpointConfig, EventExecutorGroup eventExecutorGroup, boolean isCors) { 98 | this.webSocketEndpointServer = webSocketEndpointServer; 99 | this.webSocketEndpointConfig = webSocketEndpointConfig; 100 | this.eventExecutorGroup = eventExecutorGroup; 101 | this.isCors = isCors; 102 | } 103 | 104 | /** 105 | * Receive message 106 | * @param ctx ChannelHandlerContext 107 | * @param msg FullHttpRequest 108 | */ 109 | @Override 110 | protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception { 111 | try { 112 | handleHttpRequest(ctx, msg); 113 | } 114 | catch (TypeMismatchException e) { 115 | FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST); 116 | sendHttpResponse(ctx, msg, res); 117 | log.error(e); 118 | } 119 | catch (Exception e) { 120 | FullHttpResponse res; 121 | if (internalServerErrorByteBuf != null) { 122 | res = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR, 123 | internalServerErrorByteBuf.retainedDuplicate()); 124 | } 125 | else { 126 | res = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR); 127 | } 128 | sendHttpResponse(ctx, msg, res); 129 | log.error(e); 130 | } 131 | } 132 | 133 | /** 134 | * Processing error 135 | * @param ctx ChannelHandlerContext 136 | * @param cause Throwable 137 | */ 138 | @Override 139 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 140 | webSocketEndpointServer.doOnError(ctx.channel(), cause); 141 | } 142 | 143 | /** 144 | * Close inactive connections 145 | * @param ctx ChannelHandlerContext 146 | */ 147 | @Override 148 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 149 | webSocketEndpointServer.doOnClose(ctx.channel()); 150 | super.channelInactive(ctx); 151 | } 152 | 153 | /** 154 | * Handle messages 155 | * @param ctx ChannelHandlerContext 156 | * @param req FullHttpRequest 157 | */ 158 | private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) { 159 | FullHttpResponse res; 160 | // Handle a bad request. 161 | if (!req.decoderResult().isSuccess()) { 162 | if (badRequestByteBuf != null) { 163 | res = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, badRequestByteBuf.retainedDuplicate()); 164 | } 165 | else { 166 | res = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST); 167 | } 168 | sendHttpResponse(ctx, req, res); 169 | return; 170 | } 171 | 172 | // Allow only GET methods. 173 | if (req.method() != GET) { 174 | if (forbiddenByteBuf != null) { 175 | res = new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN, forbiddenByteBuf.retainedDuplicate()); 176 | } 177 | else { 178 | res = new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN); 179 | } 180 | sendHttpResponse(ctx, req, res); 181 | return; 182 | } 183 | 184 | HttpHeaders headers = req.headers(); 185 | String host = headers.get(HttpHeaderNames.HOST); 186 | if (ObjectUtils.isEmpty(host)) { 187 | if (forbiddenByteBuf != null) { 188 | res = new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN, forbiddenByteBuf.retainedDuplicate()); 189 | } 190 | else { 191 | res = new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN); 192 | } 193 | sendHttpResponse(ctx, req, res); 194 | return; 195 | } 196 | 197 | if (!ObjectUtils.isEmpty(webSocketEndpointServer.getHost()) 198 | && !webSocketEndpointServer.getHost().equals("0.0.0.0") 199 | && !webSocketEndpointServer.getHost().equals(host.split(":")[0])) { 200 | if (forbiddenByteBuf != null) { 201 | res = new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN, forbiddenByteBuf.retainedDuplicate()); 202 | } 203 | else { 204 | res = new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN); 205 | } 206 | sendHttpResponse(ctx, req, res); 207 | return; 208 | } 209 | 210 | QueryStringDecoder decoder = new QueryStringDecoder(req.uri()); 211 | String path = decoder.path(); 212 | if ("/favicon.ico".equals(path)) { 213 | if (faviconByteBuf != null) { 214 | res = new DefaultFullHttpResponse(HTTP_1_1, OK, faviconByteBuf.retainedDuplicate()); 215 | } 216 | else { 217 | res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); 218 | } 219 | sendHttpResponse(ctx, req, res); 220 | return; 221 | } 222 | 223 | Channel channel = ctx.channel(); 224 | 225 | // path match 226 | String pattern = null; 227 | Set pathMatcherSet = webSocketEndpointServer.getPathMatcherSet(); 228 | for (WsPathMatcher pathMatcher : pathMatcherSet) { 229 | if (pathMatcher.matchAndExtract(decoder, channel)) { 230 | pattern = pathMatcher.getPattern(); 231 | break; 232 | } 233 | } 234 | 235 | if (pattern == null) { 236 | if (notFoundByteBuf != null) { 237 | res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND, notFoundByteBuf.retainedDuplicate()); 238 | } 239 | else { 240 | res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); 241 | } 242 | sendHttpResponse(ctx, req, res); 243 | return; 244 | } 245 | 246 | if (!req.headers().contains(UPGRADE) || !req.headers().contains(SEC_WEBSOCKET_KEY) 247 | || !req.headers().contains(SEC_WEBSOCKET_VERSION)) { 248 | if (forbiddenByteBuf != null) { 249 | res = new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN, forbiddenByteBuf.retainedDuplicate()); 250 | } 251 | else { 252 | res = new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN); 253 | } 254 | sendHttpResponse(ctx, req, res); 255 | return; 256 | } 257 | 258 | String subprotocols = null; 259 | 260 | if (webSocketEndpointServer.hasBeforeHandshake(channel, pattern)) { 261 | webSocketEndpointServer.doBeforeHandshake(channel, req, pattern); 262 | if (!channel.isActive()) { 263 | return; 264 | } 265 | 266 | AttributeKey subprotocolsAttrKey = AttributeKey.valueOf("subprotocols"); 267 | if (channel.hasAttr(subprotocolsAttrKey)) { 268 | subprotocols = ctx.channel().attr(subprotocolsAttrKey).get(); 269 | } 270 | } 271 | 272 | // Handshake 273 | WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), 274 | subprotocols, true, webSocketEndpointConfig.getMaxFramePayloadLength()); 275 | WebSocketServerHandshaker webSocketServerHandshaker = wsFactory.newHandshaker(req); 276 | if (webSocketServerHandshaker == null) { 277 | WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(channel); 278 | } 279 | else { 280 | ChannelPipeline pipeline = ctx.pipeline(); 281 | pipeline.remove(ctx.name()); 282 | if (webSocketEndpointConfig.getReaderIdleTimeSeconds() != 0 283 | || webSocketEndpointConfig.getWriterIdleTimeSeconds() != 0 284 | || webSocketEndpointConfig.getAllIdleTimeSeconds() != 0) { 285 | pipeline.addLast(new IdleStateHandler(webSocketEndpointConfig.getReaderIdleTimeSeconds(), 286 | webSocketEndpointConfig.getWriterIdleTimeSeconds(), 287 | webSocketEndpointConfig.getAllIdleTimeSeconds())); 288 | } 289 | if (webSocketEndpointConfig.isUseCompressionHandler()) { 290 | pipeline.addLast(new WebSocketServerCompressionHandler()); 291 | } 292 | pipeline.addLast(new WebSocketFrameAggregator(Integer.MAX_VALUE)); 293 | if (webSocketEndpointConfig.isUseEventExecutorGroup()) { 294 | pipeline.addLast(eventExecutorGroup, new WebSocketServerHandler(webSocketEndpointServer)); 295 | } 296 | else { 297 | pipeline.addLast(new WebSocketServerHandler(webSocketEndpointServer)); 298 | } 299 | String finalPattern = pattern; 300 | webSocketServerHandshaker.handshake(channel, req).addListener(future -> { 301 | if (future.isSuccess()) { 302 | if (isCors) { 303 | pipeline.remove(CorsHandler.class); 304 | } 305 | webSocketEndpointServer.doOnOpen(channel, req, finalPattern); 306 | } 307 | else { 308 | webSocketServerHandshaker.close(channel, new CloseWebSocketFrame()); 309 | } 310 | }); 311 | } 312 | 313 | } 314 | 315 | private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { 316 | // Generate an error page if response getStatus code is not OK (200). 317 | int statusCode = res.status().code(); 318 | if (statusCode != OK.code() && res.content().readableBytes() == 0) { 319 | ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); 320 | res.content().writeBytes(buf); 321 | buf.release(); 322 | } 323 | HttpUtil.setContentLength(res, res.content().readableBytes()); 324 | 325 | // Send the response and close the connection if necessary. 326 | ChannelFuture f = ctx.channel().writeAndFlush(res); 327 | if (!HttpUtil.isKeepAlive(req) || statusCode != OK.code()) { 328 | f.addListener(ChannelFutureListener.CLOSE); 329 | } 330 | } 331 | 332 | private static String getWebSocketLocation(FullHttpRequest req) { 333 | String location = req.headers().get(HttpHeaderNames.HOST) + req.uri(); 334 | return "ws://" + location; 335 | } 336 | 337 | } 338 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | cn.twelvet 8 | netty-websocket-spring-boot-starter 9 | 1.0.1 10 | 11 | netty-websocket-spring-boot-starter 12 | https://twelvet.cn 13 | High performance websocket based on netty 14 | 15 | 16 | twelvet 17 | https://twelvet.cn 18 | 19 | 20 | 21 | 22 | The Apache Software License, Version 2.0 23 | https://www.apache.org/licenses/LICENSE-2.0.txt 24 | repo 25 | 26 | 27 | 28 | 29 | https://github.com/twelvet-projects/netty-websocket-spring-boot-starter.git 30 | scm:git:ssh://git@github.com:twelvet-projects/netty-websocket-spring-boot-starter.git 31 | 32 | https://github.com/twelvet-projects/netty-websocket-spring-boot-starter 33 | 34 | 35 | 36 | 37 | L 38 | twelvet 39 | 2471835953@qq.com 40 | 41 | 42 | 43 | 44 | ossrh 45 | UTF-8 46 | UTF-8 47 | 1.8 48 | 1.8 49 | 1.8 50 | 3.11.0 51 | 3.5.0 52 | 3.2.1 53 | 1.6.13 54 | 3.0.1 55 | 0.0.39 56 | 57 | 2.7.18 58 | 4.1.101.Final 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | org.springframework.boot 68 | spring-boot-dependencies 69 | ${spring-boot-dependencies.version} 70 | pom 71 | import 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | org.springframework.boot 81 | spring-boot-autoconfigure 82 | true 83 | 84 | 85 | 86 | io.netty 87 | netty-codec-http 88 | ${netty.version} 89 | 90 | 91 | 92 | io.netty 93 | netty-handler 94 | ${netty.version} 95 | 96 | 97 | 98 | 99 | 100 | 101 | snapshot 102 | 103 | 104 | 105 | 106 | io.spring.javaformat 107 | spring-javaformat-maven-plugin 108 | ${spring.checkstyle.plugin} 109 | 110 | 111 | org.apache.maven.plugins 112 | maven-compiler-plugin 113 | ${maven.compiler.version} 114 | 115 | ${java.version} 116 | ${java.version} 117 | 118 | 119 | 120 | org.apache.maven.plugins 121 | maven-javadoc-plugin 122 | ${maven-javadoc-plugin.version} 123 | 124 | 125 | package 126 | 127 | jar 128 | 129 | 130 | 131 | 132 | 133 | org.apache.maven.plugins 134 | maven-source-plugin 135 | ${maven-source-plugin.version} 136 | 137 | 138 | ${serverId} 139 | package 140 | 141 | jar-no-fork 142 | 143 | 144 | 145 | 146 | 147 | 148 | org.sonatype.plugins 149 | nexus-staging-maven-plugin 150 | ${nexus-staging-maven-plugin.version} 151 | true 152 | 153 | ${serverId} 154 | https://s01.oss.sonatype.org/ 155 | true 156 | 157 | 158 | 159 | 160 | org.apache.maven.plugins 161 | maven-gpg-plugin 162 | ${maven-gpg-plugin.version} 163 | 164 | 165 | ${serverId} 166 | verify 167 | 168 | sign 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | sonatype 178 | 179 | https://oss.sonatype.org/content/repositories/snapshots/ 180 | 181 | 182 | 183 | 184 | 185 | release 186 | 187 | 188 | 189 | 190 | io.spring.javaformat 191 | spring-javaformat-maven-plugin 192 | ${spring.checkstyle.plugin} 193 | 194 | 195 | org.apache.maven.plugins 196 | maven-compiler-plugin 197 | ${maven.compiler.version} 198 | 199 | ${java.version} 200 | ${java.version} 201 | false 202 | 203 | -parameters 204 | 205 | 206 | 207 | 208 | org.apache.maven.plugins 209 | maven-javadoc-plugin 210 | ${maven-javadoc-plugin.version} 211 | 212 | 213 | package 214 | 215 | jar 216 | 217 | 218 | 219 | 220 | 221 | org.apache.maven.plugins 222 | maven-source-plugin 223 | ${maven-source-plugin.version} 224 | 225 | 226 | ${serverId} 227 | package 228 | 229 | jar-no-fork 230 | 231 | 232 | 233 | 234 | 235 | 236 | org.sonatype.plugins 237 | nexus-staging-maven-plugin 238 | ${nexus-staging-maven-plugin.version} 239 | true 240 | 241 | ${serverId} 242 | https://s01.oss.sonatype.org/ 243 | true 244 | 245 | 246 | 247 | 248 | org.apache.maven.plugins 249 | maven-gpg-plugin 250 | ${maven-gpg-plugin.version} 251 | 252 | 253 | ${serverId} 254 | verify 255 | 256 | sign 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | release 266 | 267 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | io.spring.javaformat 279 | spring-javaformat-maven-plugin 280 | ${spring.checkstyle.plugin} 281 | 282 | 283 | org.apache.maven.plugins 284 | maven-compiler-plugin 285 | ${maven.compiler.version} 286 | 287 | ${java.version} 288 | ${java.version} 289 | 290 | 291 | 292 | org.apache.maven.plugins 293 | maven-javadoc-plugin 294 | ${maven-javadoc-plugin.version} 295 | 296 | 297 | package 298 | 299 | jar 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/standard/WebSocketEndpointExporter.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.standard; 2 | 3 | import cn.twelvet.websocket.netty.annotation.WebSocketEndpoint; 4 | import cn.twelvet.websocket.netty.autoconfigure.annotation.EnableWebSocket; 5 | import cn.twelvet.websocket.netty.exception.WebSocketException; 6 | import cn.twelvet.websocket.netty.domain.WebSocketEndpointServer; 7 | import cn.twelvet.websocket.netty.domain.WebSocketMethodMapping; 8 | import org.springframework.beans.TypeConverter; 9 | import org.springframework.beans.TypeMismatchException; 10 | import org.springframework.beans.factory.BeanFactory; 11 | import org.springframework.beans.factory.BeanFactoryAware; 12 | import org.springframework.beans.factory.SmartInitializingSingleton; 13 | import org.springframework.beans.factory.config.BeanExpressionContext; 14 | import org.springframework.beans.factory.config.BeanExpressionResolver; 15 | import org.springframework.beans.factory.support.AbstractBeanFactory; 16 | import org.springframework.beans.factory.support.BeanDefinitionRegistry; 17 | import org.springframework.boot.autoconfigure.SpringBootApplication; 18 | import org.springframework.context.ApplicationContext; 19 | import org.springframework.context.support.ApplicationObjectSupport; 20 | import org.springframework.core.annotation.AnnotatedElementUtils; 21 | import org.springframework.core.annotation.AnnotationUtils; 22 | import org.springframework.core.io.ResourceLoader; 23 | import org.springframework.util.ClassUtils; 24 | 25 | import javax.net.ssl.SSLException; 26 | import java.net.InetSocketAddress; 27 | import java.util.*; 28 | 29 | /** 30 | * @author twelvet 扫描断点并注册 31 | */ 32 | public class WebSocketEndpointExporter extends ApplicationObjectSupport 33 | implements SmartInitializingSingleton, BeanFactoryAware { 34 | 35 | /** 36 | * 资源路径 37 | */ 38 | private final ResourceLoader resourceLoader; 39 | 40 | /** 41 | * Bean工厂 42 | */ 43 | private AbstractBeanFactory beanFactory; 44 | 45 | public WebSocketEndpointExporter(ResourceLoader resourceLoader) { 46 | this.resourceLoader = resourceLoader; 47 | } 48 | 49 | /** 50 | * 服务Map 51 | */ 52 | private static final Map addressWebsocketServerMap = new HashMap<>(); 53 | 54 | public static Map getAddressWebsocketServerMap() { 55 | return addressWebsocketServerMap; 56 | } 57 | 58 | @Override 59 | public void setBeanFactory(BeanFactory beanFactory) { 60 | if (!(beanFactory instanceof AbstractBeanFactory)) { 61 | throw new IllegalArgumentException( 62 | "AutowiredAnnotationBeanPostProcessor requires a AbstractBeanFactory: " + beanFactory); 63 | } 64 | this.beanFactory = (AbstractBeanFactory) beanFactory; 65 | } 66 | 67 | /** 68 | * 在所有bean都被放入到spring容器之后,执行WebSocket注入 69 | */ 70 | @Override 71 | public void afterSingletonsInstantiated() { 72 | registerEndpoints(); 73 | } 74 | 75 | /** 76 | * 注册实例beans 77 | */ 78 | protected void registerEndpoints() { 79 | // 容器管理 80 | ApplicationContext applicationContext = getApplicationContext(); 81 | assert applicationContext != null; 82 | // add scan endpoint 83 | scanPackage(applicationContext); 84 | 85 | String[] endpointBeanNames = applicationContext.getBeanNamesForAnnotation(WebSocketEndpoint.class); 86 | for (String beanName : endpointBeanNames) { 87 | Class endpointClass = applicationContext.getType(beanName); 88 | assert endpointClass != null; 89 | String name = endpointClass.getName(); 90 | // Whether dynamic proxy 91 | if (name.contains(ClassUtils.CGLIB_CLASS_SEPARATOR)) { 92 | registerEndpoint(endpointClass.getSuperclass()); 93 | } 94 | else { 95 | registerEndpoint(endpointClass); 96 | } 97 | } 98 | 99 | init(); 100 | } 101 | 102 | /** 103 | * add scan endpoint 104 | * @param applicationContext ApplicationContext 105 | */ 106 | private void scanPackage(ApplicationContext applicationContext) { 107 | 108 | String[] basePackages = null; 109 | 110 | // All EnableWebSocket annotation beans 111 | Map enableWebSocketBeans = applicationContext.getBeansWithAnnotation(EnableWebSocket.class); 112 | for (Object value : enableWebSocketBeans.values()) { 113 | EnableWebSocket enableWebSocket = AnnotationUtils.findAnnotation(value.getClass(), EnableWebSocket.class); 114 | assert enableWebSocket != null; 115 | // Only take the first scan path 116 | if (enableWebSocket.scanBasePackages().length != 0) { 117 | basePackages = enableWebSocket.scanBasePackages(); 118 | break; 119 | } 120 | } 121 | 122 | // use @SpringBootApplication package 123 | if (basePackages == null) { 124 | String[] springBootApplicationBeanName = applicationContext 125 | .getBeanNamesForAnnotation(SpringBootApplication.class); 126 | Object springBootApplicationBean = applicationContext.getBean(springBootApplicationBeanName[0]); 127 | SpringBootApplication springBootApplication = AnnotationUtils 128 | .findAnnotation(springBootApplicationBean.getClass(), SpringBootApplication.class); 129 | assert springBootApplication != null; 130 | if (springBootApplication.scanBasePackages().length != 0) { 131 | basePackages = springBootApplication.scanBasePackages(); 132 | } 133 | else { 134 | // Scan current application path 135 | String packageName = ClassUtils.getPackageName(springBootApplicationBean.getClass().getName()); 136 | basePackages = new String[1]; 137 | basePackages[0] = packageName; 138 | } 139 | } 140 | 141 | EndpointClassPathScanner scanHandle = new EndpointClassPathScanner((BeanDefinitionRegistry) applicationContext, 142 | false); 143 | if (resourceLoader != null) { 144 | scanHandle.setResourceLoader(resourceLoader); 145 | } 146 | 147 | // scan custom path 148 | for (String basePackage : basePackages) { 149 | scanHandle.doScan(basePackage); 150 | } 151 | } 152 | 153 | /** 154 | * 执行初始化 155 | */ 156 | private void init() { 157 | for (Map.Entry entry : addressWebsocketServerMap.entrySet()) { 158 | WebsocketServer websocketServer = entry.getValue(); 159 | try { 160 | // Start Netty 161 | websocketServer.init(); 162 | WebSocketEndpointServer webSocketEndpointServer = websocketServer.getEndpointServer(); 163 | StringJoiner stringJoiner = new StringJoiner(","); 164 | webSocketEndpointServer.getPathMatcherSet() 165 | .forEach(pathMatcher -> stringJoiner.add("'" + pathMatcher.getPattern() + "'")); 166 | logger 167 | .info(String.format("\033[34mNetty WebSocket started on port: %s with context path(s): %s .\033[0m", 168 | webSocketEndpointServer.getPort(), stringJoiner)); 169 | } 170 | catch (InterruptedException e) { 171 | logger.error(String.format("websocket [%s] init fail", entry.getKey()), e); 172 | } 173 | catch (SSLException e) { 174 | logger.error(String.format("websocket [%s] ssl create fail", entry.getKey()), e); 175 | 176 | } 177 | } 178 | } 179 | 180 | /** 181 | * 注册端点 182 | * @param endpointClass Class 183 | */ 184 | private void registerEndpoint(Class endpointClass) { 185 | WebSocketEndpoint annotation = AnnotatedElementUtils.findMergedAnnotation(endpointClass, 186 | WebSocketEndpoint.class); 187 | if (annotation == null) { 188 | throw new IllegalStateException("missingAnnotation WebSocketEndpoint"); 189 | } 190 | 191 | // Set websocket parameters 192 | WebSocketEndpointConfig webSocketEndpointConfig = buildWebSocketConfig(annotation); 193 | 194 | ApplicationContext context = getApplicationContext(); 195 | WebSocketMethodMapping webSocketMethodMapping; 196 | try { 197 | webSocketMethodMapping = new WebSocketMethodMapping(endpointClass, context, beanFactory); 198 | } 199 | catch (WebSocketException e) { 200 | throw new IllegalStateException("Failed to register WebSocketEndpointConfig: " + webSocketEndpointConfig, 201 | e); 202 | } 203 | 204 | InetSocketAddress inetSocketAddress = new InetSocketAddress(webSocketEndpointConfig.getHost(), 205 | webSocketEndpointConfig.getPort()); 206 | 207 | String path = resolveAnnotationValue(annotation.value(), String.class, "path"); 208 | 209 | WebsocketServer websocketServer = addressWebsocketServerMap.get(inetSocketAddress); 210 | if (websocketServer == null) { 211 | // Add Server 212 | WebSocketEndpointServer webSocketEndpointServer = new WebSocketEndpointServer(webSocketMethodMapping, 213 | webSocketEndpointConfig, path); 214 | websocketServer = new WebsocketServer(webSocketEndpointServer, webSocketEndpointConfig); 215 | addressWebsocketServerMap.put(inetSocketAddress, websocketServer); 216 | } 217 | else { 218 | // Add path to the same port 219 | websocketServer.getEndpointServer().addPathMethodMapping(path, webSocketMethodMapping); 220 | } 221 | } 222 | 223 | /** 224 | * set websocket parameters 225 | * @param annotation WebSocketEndpoint 226 | * @return WebSocketEndpointConfig 227 | */ 228 | private WebSocketEndpointConfig buildWebSocketConfig(WebSocketEndpoint annotation) { 229 | 230 | String host = resolveAnnotationValue(annotation.host(), String.class, "host"); 231 | int port = resolveAnnotationValue(annotation.port(), Integer.class, "port"); 232 | int bossLoopGroupThreads = resolveAnnotationValue(annotation.bossLoopGroupThreads(), Integer.class, 233 | "bossLoopGroupThreads"); 234 | int workerLoopGroupThreads = resolveAnnotationValue(annotation.workerLoopGroupThreads(), Integer.class, 235 | "workerLoopGroupThreads"); 236 | boolean useCompressionHandler = resolveAnnotationValue(annotation.useCompressionHandler(), Boolean.class, 237 | "useCompressionHandler"); 238 | 239 | int optionConnectTimeoutMillis = resolveAnnotationValue(annotation.optionConnectTimeoutMillis(), Integer.class, 240 | "optionConnectTimeoutMillis"); 241 | int optionSoBacklog = resolveAnnotationValue(annotation.optionSoBacklog(), Integer.class, "optionSoBacklog"); 242 | 243 | int childOptionWriteSpinCount = resolveAnnotationValue(annotation.childOptionWriteSpinCount(), Integer.class, 244 | "childOptionWriteSpinCount"); 245 | int childOptionWriteBufferHighWaterMark = resolveAnnotationValue( 246 | annotation.childOptionWriteBufferHighWaterMark(), Integer.class, "childOptionWriteBufferHighWaterMark"); 247 | int childOptionWriteBufferLowWaterMark = resolveAnnotationValue(annotation.childOptionWriteBufferLowWaterMark(), 248 | Integer.class, "childOptionWriteBufferLowWaterMark"); 249 | int childOptionSoRcvbuf = resolveAnnotationValue(annotation.childOptionSoRcvbuf(), Integer.class, 250 | "childOptionSoRcvbuf"); 251 | int childOptionSoSndbuf = resolveAnnotationValue(annotation.childOptionSoSndbuf(), Integer.class, 252 | "childOptionSoSndbuf"); 253 | boolean childOptionTcpNodelay = resolveAnnotationValue(annotation.childOptionTcpNodelay(), Boolean.class, 254 | "childOptionTcpNodelay"); 255 | boolean childOptionSoKeepalive = resolveAnnotationValue(annotation.childOptionSoKeepalive(), Boolean.class, 256 | "childOptionSoKeepalive"); 257 | int childOptionSoLinger = resolveAnnotationValue(annotation.childOptionSoLinger(), Integer.class, 258 | "childOptionSoLinger"); 259 | boolean childOptionAllowHalfClosure = resolveAnnotationValue(annotation.childOptionAllowHalfClosure(), 260 | Boolean.class, "childOptionAllowHalfClosure"); 261 | 262 | int readerIdleTimeSeconds = resolveAnnotationValue(annotation.readerIdleTimeSeconds(), Integer.class, 263 | "readerIdleTimeSeconds"); 264 | int writerIdleTimeSeconds = resolveAnnotationValue(annotation.writerIdleTimeSeconds(), Integer.class, 265 | "writerIdleTimeSeconds"); 266 | int allIdleTimeSeconds = resolveAnnotationValue(annotation.allIdleTimeSeconds(), Integer.class, 267 | "allIdleTimeSeconds"); 268 | 269 | int maxFramePayloadLength = resolveAnnotationValue(annotation.maxFramePayloadLength(), Integer.class, 270 | "maxFramePayloadLength"); 271 | 272 | boolean useEventExecutorGroup = resolveAnnotationValue(annotation.useEventExecutorGroup(), Boolean.class, 273 | "useEventExecutorGroup"); 274 | int eventExecutorGroupThreads = resolveAnnotationValue(annotation.eventExecutorGroupThreads(), Integer.class, 275 | "eventExecutorGroupThreads"); 276 | 277 | String sslKeyPassword = resolveAnnotationValue(annotation.sslKeyPassword(), String.class, "sslKeyPassword"); 278 | String sslKeyStore = resolveAnnotationValue(annotation.sslKeyStore(), String.class, "sslKeyStore"); 279 | String sslKeyStorePassword = resolveAnnotationValue(annotation.sslKeyStorePassword(), String.class, 280 | "sslKeyStorePassword"); 281 | String sslKeyStoreType = resolveAnnotationValue(annotation.sslKeyStoreType(), String.class, "sslKeyStoreType"); 282 | String sslTrustStore = resolveAnnotationValue(annotation.sslTrustStore(), String.class, "sslTrustStore"); 283 | String sslTrustStorePassword = resolveAnnotationValue(annotation.sslTrustStorePassword(), String.class, 284 | "sslTrustStorePassword"); 285 | String sslTrustStoreType = resolveAnnotationValue(annotation.sslTrustStoreType(), String.class, 286 | "sslTrustStoreType"); 287 | 288 | // corsOrigins 289 | Boolean corsAllowCredentials = resolveAnnotationValue(annotation.corsAllowCredentials(), Boolean.class, 290 | "corsAllowCredentials"); 291 | String[] corsOrigins = annotation.corsOrigins(); 292 | if (corsOrigins.length != 0) { 293 | for (int i = 0; i < corsOrigins.length; i++) { 294 | corsOrigins[i] = resolveAnnotationValue(corsOrigins[i], String.class, "corsOrigins"); 295 | } 296 | } 297 | 298 | return new WebSocketEndpointConfig(host, port, bossLoopGroupThreads, workerLoopGroupThreads, 299 | useCompressionHandler, optionConnectTimeoutMillis, optionSoBacklog, childOptionWriteSpinCount, 300 | childOptionWriteBufferHighWaterMark, childOptionWriteBufferLowWaterMark, childOptionSoRcvbuf, 301 | childOptionSoSndbuf, childOptionTcpNodelay, childOptionSoKeepalive, childOptionSoLinger, 302 | childOptionAllowHalfClosure, readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds, 303 | maxFramePayloadLength, useEventExecutorGroup, eventExecutorGroupThreads, sslKeyPassword, sslKeyStore, 304 | sslKeyStorePassword, sslKeyStoreType, sslTrustStore, sslTrustStorePassword, sslTrustStoreType, 305 | corsOrigins, corsAllowCredentials); 306 | } 307 | 308 | /** 309 | * Set parameters and support SpEL expressions 310 | * @param value value 311 | * @param requiredType Parameter type 312 | * @param paramName paramName 313 | * @param T 314 | * @return T 315 | */ 316 | private T resolveAnnotationValue(Object value, Class requiredType, String paramName) { 317 | 318 | if (value instanceof String) { 319 | // SpEL Get configuration 320 | String strVal = beanFactory.resolveEmbeddedValue((String) value); 321 | BeanExpressionResolver beanExpressionResolver = beanFactory.getBeanExpressionResolver(); 322 | if (beanExpressionResolver != null) { 323 | // SpEL operation 324 | value = beanExpressionResolver.evaluate(strVal, new BeanExpressionContext(beanFactory, null)); 325 | } 326 | else { 327 | value = strVal; 328 | } 329 | } 330 | 331 | // convert type 332 | try { 333 | TypeConverter typeConverter = beanFactory.getTypeConverter(); 334 | return typeConverter.convertIfNecessary(value, requiredType); 335 | } 336 | catch (TypeMismatchException e) { 337 | throw new IllegalArgumentException("Failed to convert value of parameter '" + paramName 338 | + "' to required type '" + requiredType.getName() + "'"); 339 | } 340 | } 341 | 342 | } 343 | -------------------------------------------------------------------------------- /src/main/java/cn/twelvet/websocket/netty/domain/WebSocketMethodMapping.java: -------------------------------------------------------------------------------- 1 | package cn.twelvet.websocket.netty.domain; 2 | 3 | import cn.twelvet.websocket.netty.support.impl.*; 4 | import io.netty.channel.Channel; 5 | import io.netty.handler.codec.http.FullHttpRequest; 6 | import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; 7 | import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; 8 | import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor; 9 | import org.springframework.beans.factory.support.AbstractBeanFactory; 10 | import org.springframework.context.ApplicationContext; 11 | import org.springframework.core.DefaultParameterNameDiscoverer; 12 | import org.springframework.core.MethodParameter; 13 | import org.springframework.core.ParameterNameDiscoverer; 14 | import cn.twelvet.websocket.netty.annotation.*; 15 | import cn.twelvet.websocket.netty.exception.WebSocketException; 16 | import cn.twelvet.websocket.netty.support.*; 17 | 18 | import java.lang.annotation.Annotation; 19 | import java.lang.reflect.InvocationTargetException; 20 | import java.lang.reflect.Method; 21 | import java.lang.reflect.Modifier; 22 | import java.util.ArrayList; 23 | import java.util.Arrays; 24 | import java.util.List; 25 | 26 | /** 27 | * @author twelvet 断点方法注入参数 28 | */ 29 | public class WebSocketMethodMapping { 30 | 31 | private static final ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); 32 | 33 | private final Method beforeHandshake; 34 | 35 | private final Method onOpen; 36 | 37 | private final Method onClose; 38 | 39 | private final Method onError; 40 | 41 | private final Method onMessage; 42 | 43 | private final Method onBinary; 44 | 45 | private final Method onEvent; 46 | 47 | private final MethodParameter[] beforeHandshakeParameters; 48 | 49 | private final MethodParameter[] onOpenParameters; 50 | 51 | private final MethodParameter[] onCloseParameters; 52 | 53 | private final MethodParameter[] onErrorParameters; 54 | 55 | private final MethodParameter[] onMessageParameters; 56 | 57 | private final MethodParameter[] onBinaryParameters; 58 | 59 | private final MethodParameter[] onEventParameters; 60 | 61 | private final MethodArgumentResolver[] beforeHandshakeArgResolvers; 62 | 63 | private final MethodArgumentResolver[] onOpenArgResolvers; 64 | 65 | private final MethodArgumentResolver[] onCloseArgResolvers; 66 | 67 | private final MethodArgumentResolver[] onErrorArgResolvers; 68 | 69 | private final MethodArgumentResolver[] onMessageArgResolvers; 70 | 71 | private final MethodArgumentResolver[] onBinaryArgResolvers; 72 | 73 | private final MethodArgumentResolver[] onEventArgResolvers; 74 | 75 | private final Class webSocketClazz; 76 | 77 | private final ApplicationContext applicationContext; 78 | 79 | private final AbstractBeanFactory beanFactory; 80 | 81 | public WebSocketMethodMapping(Class webSocketClazz, ApplicationContext context, AbstractBeanFactory beanFactory) 82 | throws WebSocketException { 83 | this.applicationContext = context; 84 | this.webSocketClazz = webSocketClazz; 85 | this.beanFactory = beanFactory; 86 | Method handshake = null; 87 | Method open = null; 88 | Method close = null; 89 | Method error = null; 90 | Method message = null; 91 | Method binary = null; 92 | Method event = null; 93 | Method[] webSocketClazzMethods = null; 94 | Class currentClazz = webSocketClazz; 95 | 96 | // Find parent class 97 | while (!currentClazz.equals(Object.class)) { 98 | Method[] currentClazzMethods = currentClazz.getDeclaredMethods(); 99 | if (currentClazz == webSocketClazz) { 100 | webSocketClazzMethods = currentClazzMethods; 101 | } 102 | // Rewriting method does not allow multiple annotations 103 | for (Method method : currentClazzMethods) { 104 | if (method.getAnnotation(BeforeHandshake.class) != null) { 105 | checkIsPublic(method); 106 | if (handshake == null) { 107 | handshake = method; 108 | } 109 | else { 110 | if (currentClazz == webSocketClazz || !isMethodOverride(handshake, method)) { 111 | // Duplicate annotation 112 | throw new WebSocketException("duplicateAnnotation BeforeHandshake"); 113 | } 114 | } 115 | } 116 | else if (method.getAnnotation(OnOpen.class) != null) { 117 | checkIsPublic(method); 118 | if (open == null) { 119 | open = method; 120 | } 121 | else { 122 | if (currentClazz == webSocketClazz || !isMethodOverride(open, method)) { 123 | // Duplicate annotation 124 | throw new WebSocketException("duplicateAnnotation OnOpen"); 125 | } 126 | } 127 | } 128 | else if (method.getAnnotation(OnClose.class) != null) { 129 | checkIsPublic(method); 130 | if (close == null) { 131 | close = method; 132 | } 133 | else { 134 | if (currentClazz == webSocketClazz || !isMethodOverride(close, method)) { 135 | // Duplicate annotation 136 | throw new WebSocketException("duplicateAnnotation OnClose"); 137 | } 138 | } 139 | } 140 | else if (method.getAnnotation(OnError.class) != null) { 141 | checkIsPublic(method); 142 | if (error == null) { 143 | error = method; 144 | } 145 | else { 146 | if (currentClazz == webSocketClazz || !isMethodOverride(error, method)) { 147 | // Duplicate annotation 148 | throw new WebSocketException("duplicateAnnotation OnError"); 149 | } 150 | } 151 | } 152 | else if (method.getAnnotation(OnMessage.class) != null) { 153 | checkIsPublic(method); 154 | if (message == null) { 155 | message = method; 156 | } 157 | else { 158 | if (currentClazz == webSocketClazz || !isMethodOverride(message, method)) { 159 | // Duplicate annotation 160 | throw new WebSocketException("duplicateAnnotation onMessage"); 161 | } 162 | } 163 | } 164 | else if (method.getAnnotation(OnBinary.class) != null) { 165 | checkIsPublic(method); 166 | if (binary == null) { 167 | binary = method; 168 | } 169 | else { 170 | if (currentClazz == webSocketClazz || !isMethodOverride(binary, method)) { 171 | // Duplicate annotation 172 | throw new WebSocketException("duplicateAnnotation OnBinary"); 173 | } 174 | } 175 | } 176 | else if (method.getAnnotation(OnEvent.class) != null) { 177 | checkIsPublic(method); 178 | if (event == null) { 179 | event = method; 180 | } 181 | else { 182 | if (currentClazz == webSocketClazz || !isMethodOverride(event, method)) { 183 | // Duplicate annotation 184 | throw new WebSocketException("duplicateAnnotation OnEvent"); 185 | } 186 | } 187 | } 188 | else { 189 | // Method not annotated 190 | } 191 | } 192 | // Continue to get the previous level 193 | currentClazz = currentClazz.getSuperclass(); 194 | } 195 | 196 | // When the method is rewritten and there is no annotation, the parent annotation 197 | // function of this method will be cancelled 198 | if (handshake != null && handshake.getDeclaringClass() != webSocketClazz) { 199 | if (isOverrideWithoutAnnotation(webSocketClazzMethods, handshake, BeforeHandshake.class)) { 200 | handshake = null; 201 | } 202 | } 203 | if (open != null && open.getDeclaringClass() != webSocketClazz) { 204 | if (isOverrideWithoutAnnotation(webSocketClazzMethods, open, OnOpen.class)) { 205 | open = null; 206 | } 207 | } 208 | if (close != null && close.getDeclaringClass() != webSocketClazz) { 209 | if (isOverrideWithoutAnnotation(webSocketClazzMethods, close, OnClose.class)) { 210 | close = null; 211 | } 212 | } 213 | if (error != null && error.getDeclaringClass() != webSocketClazz) { 214 | if (isOverrideWithoutAnnotation(webSocketClazzMethods, error, OnError.class)) { 215 | error = null; 216 | } 217 | } 218 | if (message != null && message.getDeclaringClass() != webSocketClazz) { 219 | if (isOverrideWithoutAnnotation(webSocketClazzMethods, message, OnMessage.class)) { 220 | message = null; 221 | } 222 | } 223 | if (binary != null && binary.getDeclaringClass() != webSocketClazz) { 224 | if (isOverrideWithoutAnnotation(webSocketClazzMethods, binary, OnBinary.class)) { 225 | binary = null; 226 | } 227 | } 228 | if (event != null && event.getDeclaringClass() != webSocketClazz) { 229 | if (isOverrideWithoutAnnotation(webSocketClazzMethods, event, OnEvent.class)) { 230 | event = null; 231 | } 232 | } 233 | 234 | this.beforeHandshake = handshake; 235 | this.onOpen = open; 236 | this.onClose = close; 237 | this.onError = error; 238 | this.onMessage = message; 239 | this.onBinary = binary; 240 | this.onEvent = event; 241 | 242 | // Get parameters 243 | beforeHandshakeParameters = getParameters(beforeHandshake); 244 | onOpenParameters = getParameters(onOpen); 245 | onCloseParameters = getParameters(onClose); 246 | onMessageParameters = getParameters(onMessage); 247 | onErrorParameters = getParameters(onError); 248 | onBinaryParameters = getParameters(onBinary); 249 | onEventParameters = getParameters(onEvent); 250 | 251 | // Get parser 252 | beforeHandshakeArgResolvers = getResolvers(beforeHandshakeParameters); 253 | onOpenArgResolvers = getResolvers(onOpenParameters); 254 | onCloseArgResolvers = getResolvers(onCloseParameters); 255 | onMessageArgResolvers = getResolvers(onMessageParameters); 256 | onErrorArgResolvers = getResolvers(onErrorParameters); 257 | onBinaryArgResolvers = getResolvers(onBinaryParameters); 258 | onEventArgResolvers = getResolvers(onEventParameters); 259 | } 260 | 261 | /** 262 | * Check whether it is public 263 | * @param m Method 264 | */ 265 | private void checkIsPublic(Method m) throws WebSocketException { 266 | if (!Modifier.isPublic(m.getModifiers())) { 267 | throw new WebSocketException("methodNotPublic " + m.getName()); 268 | } 269 | } 270 | 271 | /** 272 | * Whether the judgment method is consistent 273 | * @param method1 子方法 274 | * @param method2 父方法 275 | * @return boolean 276 | */ 277 | private boolean isMethodOverride(Method method1, Method method2) { 278 | // methodName 279 | return (method1.getName().equals(method2.getName()) 280 | // return type 281 | && method1.getReturnType().equals(method2.getReturnType()) 282 | // params 283 | && Arrays.equals(method1.getParameterTypes(), method2.getParameterTypes())); 284 | } 285 | 286 | /** 287 | * Whether the rewriting method changes the annotation 288 | * @param methods All methods of class 289 | * @param superClazzMethod superClazzMethod annotation 290 | * @param annotation annotation 291 | * @return boolean 292 | */ 293 | private boolean isOverrideWithoutAnnotation(Method[] methods, Method superClazzMethod, 294 | Class annotation) { 295 | for (Method method : methods) { 296 | // Whether the method is overridden and whether the obtained annotation is 297 | // empty 298 | if (isMethodOverride(method, superClazzMethod) && (method.getAnnotation(annotation) == null)) { 299 | return true; 300 | } 301 | } 302 | return false; 303 | } 304 | 305 | Object getEndpointInstance() 306 | throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { 307 | Object implement = webSocketClazz.getDeclaredConstructor().newInstance(); 308 | AutowiredAnnotationBeanPostProcessor postProcessor = applicationContext 309 | .getBean(AutowiredAnnotationBeanPostProcessor.class); 310 | postProcessor.postProcessProperties(null, implement, null); 311 | return implement; 312 | } 313 | 314 | Method getBeforeHandshake() { 315 | return beforeHandshake; 316 | } 317 | 318 | Object[] getBeforeHandshakeArgs(Channel channel, FullHttpRequest req) throws Exception { 319 | return getMethodArgumentValues(channel, req, beforeHandshakeParameters, beforeHandshakeArgResolvers); 320 | } 321 | 322 | Method getOnOpen() { 323 | return onOpen; 324 | } 325 | 326 | Object[] getOnOpenArgs(Channel channel, FullHttpRequest req) throws Exception { 327 | return getMethodArgumentValues(channel, req, onOpenParameters, onOpenArgResolvers); 328 | } 329 | 330 | MethodArgumentResolver[] getOnOpenArgResolvers() { 331 | return onOpenArgResolvers; 332 | } 333 | 334 | Method getOnClose() { 335 | return onClose; 336 | } 337 | 338 | Object[] getOnCloseArgs(Channel channel) throws Exception { 339 | return getMethodArgumentValues(channel, null, onCloseParameters, onCloseArgResolvers); 340 | } 341 | 342 | Method getOnError() { 343 | return onError; 344 | } 345 | 346 | Object[] getOnErrorArgs(Channel channel, Throwable throwable) throws Exception { 347 | return getMethodArgumentValues(channel, throwable, onErrorParameters, onErrorArgResolvers); 348 | } 349 | 350 | Method getOnMessage() { 351 | return onMessage; 352 | } 353 | 354 | Object[] getOnMessageArgs(Channel channel, TextWebSocketFrame textWebSocketFrame) throws Exception { 355 | return getMethodArgumentValues(channel, textWebSocketFrame, onMessageParameters, onMessageArgResolvers); 356 | } 357 | 358 | Method getOnBinary() { 359 | return onBinary; 360 | } 361 | 362 | Object[] getOnBinaryArgs(Channel channel, BinaryWebSocketFrame binaryWebSocketFrame) throws Exception { 363 | return getMethodArgumentValues(channel, binaryWebSocketFrame, onBinaryParameters, onBinaryArgResolvers); 364 | } 365 | 366 | Method getOnEvent() { 367 | return onEvent; 368 | } 369 | 370 | Object[] getOnEventArgs(Channel channel, Object evt) throws Exception { 371 | return getMethodArgumentValues(channel, evt, onEventParameters, onEventArgResolvers); 372 | } 373 | 374 | /** 375 | * Get all params 376 | * @param channel Channel 377 | * @param object Object 378 | * @param parameters MethodParameter[] 379 | * @param resolvers MethodArgumentResolver 380 | * @return Object[] 381 | */ 382 | private Object[] getMethodArgumentValues(Channel channel, Object object, MethodParameter[] parameters, 383 | MethodArgumentResolver[] resolvers) throws Exception { 384 | Object[] objects = new Object[parameters.length]; 385 | for (int i = 0; i < parameters.length; i++) { 386 | MethodParameter parameter = parameters[i]; 387 | MethodArgumentResolver resolver = resolvers[i]; 388 | Object arg = resolver.resolveArgument(parameter, channel, object); 389 | objects[i] = arg; 390 | } 391 | return objects; 392 | } 393 | 394 | /** 395 | * Get all parsers 396 | * @param parameters MethodParameter[] 397 | * @return MethodArgumentResolver[] 398 | */ 399 | private MethodArgumentResolver[] getResolvers(MethodParameter[] parameters) throws WebSocketException { 400 | MethodArgumentResolver[] methodArgumentResolvers = new MethodArgumentResolver[parameters.length]; 401 | List resolvers = getDefaultResolvers(); 402 | 403 | for (int i = 0; i < parameters.length; i++) { 404 | MethodParameter parameter = parameters[i]; 405 | for (MethodArgumentResolver resolver : resolvers) { 406 | if (resolver.supportsParameter(parameter)) { 407 | methodArgumentResolvers[i] = resolver; 408 | break; 409 | } 410 | } 411 | if (methodArgumentResolvers[i] == null) { 412 | throw new WebSocketException("paramClassIncorrect parameter name : " + parameter.getParameterName()); 413 | } 414 | } 415 | 416 | return methodArgumentResolvers; 417 | } 418 | 419 | /** 420 | * Add netty parser 421 | * @return List 422 | */ 423 | private List getDefaultResolvers() { 424 | List resolvers = new ArrayList<>(); 425 | resolvers.add(new SessionMethodArgumentResolver()); 426 | resolvers.add(new HttpHeadersMethodArgumentResolver()); 427 | resolvers.add(new TextMethodArgumentResolver()); 428 | resolvers.add(new ThrowableMethodArgumentResolver()); 429 | resolvers.add(new ByteMethodArgumentResolver()); 430 | resolvers.add(new RequestParamMapMethodArgumentResolver()); 431 | resolvers.add(new RequestParamMethodArgumentResolver(beanFactory)); 432 | resolvers.add(new PathVariableMapMethodArgumentResolver()); 433 | resolvers.add(new PathVariableMethodArgumentResolver(beanFactory)); 434 | resolvers.add(new EventMethodArgumentResolver(beanFactory)); 435 | return resolvers; 436 | } 437 | 438 | /** 439 | * Get all parameters 440 | * @param method Method 441 | * @return Method params 442 | */ 443 | private static MethodParameter[] getParameters(Method method) { 444 | if (method == null) { 445 | return new MethodParameter[0]; 446 | } 447 | int paramsCount = method.getParameterCount(); 448 | MethodParameter[] result = new MethodParameter[paramsCount]; 449 | for (int i = 0; i < paramsCount; i++) { 450 | MethodParameter methodParameter = new MethodParameter(method, i); 451 | methodParameter.initParameterNameDiscovery(parameterNameDiscoverer); 452 | result[i] = methodParameter; 453 | } 454 | return result; 455 | } 456 | 457 | } 458 | --------------------------------------------------------------------------------