Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🚀 lightweight high-performance WebSocket framework ( 轻量级、高性能的WebSocket框架)

License

NotificationsYou must be signed in to change notification settings

YeautyYE/netty-websocket-spring-boot-starter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

中文文档 (Chinese Docs)

About

netty-websocket-spring-boot-starter will help you develop WebSocket server by using Netty in spring-boot,it is easy to develop by using annotation like spring-websocket

Requirement

  • jdk version 17

Quick Start

  • add Dependencies:
<dependency><groupId>org.yeauty</groupId><artifactId>netty-websocket-spring-boot-starter</artifactId><version>0.13.0</version></dependency>
  • annotate@ServerEndpoint on endpoint class,and annotate@BeforeHandshake,@OnOpen,@OnClose,@OnError,@OnMessage,@OnBinary,@OnEvent on the method. e.g.
@ServerEndpoint(path ="/ws/{arg}")publicclassMyWebSocket {@BeforeHandshakepublicvoidhandshake(Sessionsession,HttpHeadersheaders,@RequestParamStringreq,@RequestParamMultiValueMapreqMap,@PathVariableStringarg,@PathVariableMappathMap){session.setSubprotocols("stomp");if (!"ok".equals(req)){System.out.println("Authentication failed!");session.close();        }    }@OnOpenpublicvoidonOpen(Sessionsession,HttpHeadersheaders,@RequestParamStringreq,@RequestParamMultiValueMapreqMap,@PathVariableStringarg,@PathVariableMappathMap){System.out.println("new connection");System.out.println(req);    }@OnClosepublicvoidonClose(Sessionsession)throwsIOException {System.out.println("one connection closed");     }@OnErrorpublicvoidonError(Sessionsession,Throwablethrowable) {throwable.printStackTrace();    }@OnMessagepublicvoidonMessage(Sessionsession,Stringmessage) {System.out.println(message);session.sendText("Hello Netty!");    }@OnBinarypublicvoidonBinary(Sessionsession,byte[]bytes) {for (byteb :bytes) {System.out.println(b);        }session.sendBinary(bytes);     }@OnEventpublicvoidonEvent(Sessionsession,Objectevt) {if (evtinstanceofIdleStateEvent) {IdleStateEventidleStateEvent = (IdleStateEvent)evt;switch (idleStateEvent.state()) {caseREADER_IDLE:System.out.println("read idle");break;caseWRITER_IDLE:System.out.println("write idle");break;caseALL_IDLE:System.out.println("all idle");break;default:break;            }        }    }}
  • use Websocket client to connectws://127.0.0.1:80/ws/xxx

Annotation

@ServerEndpoint

declaringServerEndpointExporter in Spring configuration,it will scan for WebSocket endpoints that be annotated withServerEndpoint .beans that be annotated withServerEndpoint will be registered as a WebSocket endpoint.allconfigurations are inside this annotation ( e.g.@ServerEndpoint("/ws") )

@BeforeHandshake

when there is a connection accepted,the method annotated with@BeforeHandshake will be called
classes which be injected to the method are:Session,HttpHeaders...

@OnOpen

when there is a WebSocket connection completed,the method annotated with@OnOpen will be called
classes which be injected to the method are:Session,HttpHeaders...

@OnClose

when a WebSocket connection closed,the method annotated with@OnClose will be calledclasses which be injected to the method are:Session

@OnError

when a WebSocket connection throw Throwable, the method annotated with@OnError will be calledclasses which be injected to the method are:Session,Throwable

@OnMessage

when a WebSocket connection received a message,the method annotated with@OnMessage will be calledclasses which be injected to the method are:Session,String

@OnBinary

when a WebSocket connection received the binary,the method annotated with@OnBinary will be calledclasses which be injected to the method are:Session,byte[]

@OnEvent

when a WebSocket connection received the event of Netty,the method annotated with@OnEvent will be calledclasses which be injected to the method are:Session,Object

Configuration

all configurations are configured in@ServerEndpoint's property

propertydefaultdescription
path"/"path of WebSocket can be aliased forvalue
host"0.0.0.0"host of WebSocket."0.0.0.0" means all of local addresses
port80port of WebSocket。if the port equals to 0,it will use a random and available port(to get the portMulti-Endpoint)
bossLoopGroupThreads0num of threads in bossEventLoopGroup
workerLoopGroupThreads0num of threads in workerEventLoopGroup
useCompressionHandlerfalsewhether add WebSocketServerCompressionHandler to pipeline
optionConnectTimeoutMillis30000the same asChannelOption.CONNECT_TIMEOUT_MILLIS in Netty
optionSoBacklog128the same asChannelOption.SO_BACKLOG in Netty
childOptionWriteSpinCount16the same asChannelOption.WRITE_SPIN_COUNT in Netty
childOptionWriteBufferHighWaterMark64*1024the same asChannelOption.WRITE_BUFFER_HIGH_WATER_MARK in Netty,but useChannelOption.WRITE_BUFFER_WATER_MARK in fact.
childOptionWriteBufferLowWaterMark32*1024the same asChannelOption.WRITE_BUFFER_LOW_WATER_MARK in Netty,but useChannelOption.WRITE_BUFFER_WATER_MARK in fact.
childOptionSoRcvbuf-1(mean not set)the same asChannelOption.SO_RCVBUF in Netty
childOptionSoSndbuf-1(mean not set)the same asChannelOption.SO_SNDBUF in Netty
childOptionTcpNodelaytruethe same asChannelOption.TCP_NODELAY in Netty
childOptionSoKeepalivefalsethe same asChannelOption.SO_KEEPALIVE in Netty
childOptionSoLinger-1the same asChannelOption.SO_LINGER in Netty
childOptionAllowHalfClosurefalsethe same asChannelOption.ALLOW_HALF_CLOSURE in Netty
readerIdleTimeSeconds0the same asreaderIdleTimeSeconds inIdleStateHandler and addIdleStateHandler topipeline when it is not 0
writerIdleTimeSeconds0the same aswriterIdleTimeSeconds inIdleStateHandler and addIdleStateHandler topipeline when it is not 0
allIdleTimeSeconds0the same asallIdleTimeSeconds inIdleStateHandler and addIdleStateHandler topipeline when it is not 0
maxFramePayloadLength65536Maximum allowable frame payload length.
useEventExecutorGrouptrueWhether to use another thread pool to perform time-consuming synchronous business logic
eventExecutorGroupThreads16num of threads in bossEventLoopGroup
sslKeyPassword""(mean not set)the same asserver.ssl.key-password in spring-boot
sslKeyStore""(mean not set)the same asserver.ssl.key-store in spring-boot
sslKeyStorePassword""(mean not set)the same asserver.ssl.key-store-password in spring-boot
sslKeyStoreType""(mean not set)the same asserver.ssl.key-store-type in spring-boot
sslTrustStore""(mean not set)the same asserver.ssl.trust-store in spring-boot
sslTrustStorePassword""(mean not set)the same asserver.ssl.trust-store-password in spring-boot
sslTrustStoreType""(mean not set)the same asserver.ssl.trust-store-type in spring-boot
corsOrigins{}(mean not set)the same as@CrossOrigin#origins in spring-boot
corsAllowCredentials""(mean not set)the same as@CrossOrigin#allowCredentials in spring-boot

Configuration by application.properties

You can get the configurate ofapplication.properties by using${...} placeholders. for example:

  • first,use${...} in@ServerEndpoint
@ServerEndpoint(host ="${ws.host}",port ="${ws.port}")publicclassMyWebSocket {    ...}
  • then configurate inapplication.properties
ws.host=0.0.0.0ws.port=80

Custom Favicon

The way of configure favicon is the same as spring-boot.Iffavicon.ico is presented in the root of the classpath,it will be automatically used as the favicon of the application.the example is following:

src/  +- main/      +- java/      |   + <source code>      +- resources/          +- favicon.ico

Custom Error Pages

The way of configure favicon is the same as spring-boot.you can add a file to an/public/errorfolder.The name of the error page should be the exact status code or a series mask.the example is following:

src/  +- main/      +- java/      |   + <source code>      +- resources/          +- public/              +- error/              |   +- 404.html              |   +- 5xx.html              +- <other public assets>

Multi Endpoint

  • base onQuick-Start,use annotation@ServerEndpoint and@Component in classes which hope to become a endpoint.
  • you can get all socket addresses inServerEndpointExporter.getInetSocketAddressSet().
  • when there are different addresses(different host or different port) in WebSocket,they will use differentServerBootstrap instance.
  • when the addresses are the same,but path is different,they will use the sameServerBootstrap instance.
  • when multiple port of endpoint is 0 ,they will use the same random port
  • 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

Change Log

0.8.0

  • Auto-Configuration

0.9.0

  • Support RESTful by@PathVariable
  • Get param by@RequestParam from query
  • RemoveParameterMap ,instead of@RequestParam MultiValueMap
  • Add@BeforeHandshake annotation,you can close the connect before handshake
  • Set sub-protocol in@BeforeHandshake event
  • Remove the@Component on endpoint class
  • UpdateNetty version to4.1.44.Final

0.9.1

  • Bug fixed : it was null when using@RequestParam MultiValueMap to get value
  • UpdateNetty version to4.1.45.Final

0.9.2

  • There are compatibility version under 0.8.0 that can configure theServerEndpointExporter manully

0.9.3

  • Bug fixed :when there is no@BeforeHandshake , NullPointerException will appear

0.9.4

  • Bug fixed :when there is no@BeforeHandshake ,Session inOnOpen is null

0.9.5

  • Bug fixed :Throwable inOnError event is null

0.10.0

  • Modified the default value ofbossLoopGroupThreads to 1
  • Supports configuringuseEventExecutorGroup to run synchronous and time-consuming business logic in EventExecutorGroup, so that the I/O thread is not blocked by a time-consuming task
  • SSL supported
  • CORS supported
  • UpdateNetty version to4.1.49.Final

0.11.0

  • When theServerEndpoint class is proxied by CGLIB (as with AOP enhancement), it still works

0.12.0

  • @enableWebSocket adds thescanBasePackages attribute
  • @serverEndpoint no longer depends on@Component
  • UpdateNetty version to4.1.67.Final

0.13.0

  • Fixed the issue where WebSocket compression was not working.
  • Upgraded support for Spring Boot 3.
  • Included the client'sSec-WebSocket-Protocol in the response header.
  • When closing the connection, sends abye command first instead of directly closing.
  • UpdatedNetty version to4.1.118.Final.

About

🚀 lightweight high-performance WebSocket framework ( 轻量级、高性能的WebSocket框架)

Topics

Resources

License

Stars

Watchers

Forks

Contributors7

Languages


[8]ページ先頭

©2009-2025 Movatter.jp