SpringBoot2+Netty+WebSocket(netty實現websocket,支援URL引數)
阿新 • • 發佈:2021-01-07
關於Netty
Netty 是一個利用 Java 的高階網路的能力,隱藏其背後的複雜性而提供一個易於使用的 API 的客戶端/伺服器框架。
更新
- 2019-7-11 新增URL引數支援,並解決了帶參URL導致的連線自動斷開問題,感謝大家的支援。
MAVEN依賴
<dependencies>
<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.36.Final</version>
</dependency>
</dependencies>
SpringBootApplication
啟動器中需要new一個NettyServer,並顯式呼叫啟動netty。
@SpringBootApplication
public class SpringCloudStudyDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudStudyDemoApplication.class,args);
try {
new NettyServer(12345).start();
System.out.println("https://blog.csdn.net/moshowgame");
System.out.println("http://127.0.0.1:6688/netty-websocket/index");
}catch(Exception e) {
System.out.println("NettyServerError:"+e.getMessage());
}
}
}
NettyServer
啟動的NettyServer,這裡進行配置
/**
* NettyServer Netty伺服器配置
* @author zhengkai.blog.csdn.net
* @date 2019-06-12
*/
public class NettyServer {
private final int port;
public NettyServer(int port) {
this.port = port;
}
public void start() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap sb = new ServerBootstrap();
sb.option(ChannelOption.SO_BACKLOG, 1024);
sb.group(group, bossGroup) // 繫結執行緒池
.channel(NioServerSocketChannel.class) // 指定使用的channel
.localAddress(this.port)// 繫結監聽埠
.childHandler(new ChannelInitializer<SocketChannel>() { // 繫結客戶端連線時候觸發操作
@Override
protected void initChannel(SocketChannel ch) throws Exception {
System.out.println("收到新連線");
//websocket協議本身是基於http協議的,所以這邊也要使用http解編碼器
ch.pipeline().addLast(new HttpServerCodec());
//以塊的方式來寫的處理器
ch.pipeline().addLast(new ChunkedWriteHandler());
ch.pipeline().addLast(new HttpObjectAggregator(8192));
ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", null, true, 65536 * 10));
ch.pipeline().addLast(new MyWebSocketHandler());
}
});
ChannelFuture cf = sb.bind().sync(); // 伺服器非同步建立繫結
System.out.println(NettyServer.class + " 啟動正在監聽: " + cf.channel().localAddress());
cf.channel().closeFuture().sync(); // 關閉伺服器通道
} finally {
group.shutdownGracefully().sync(); // 釋放執行緒池資源
bossGroup.shutdownGracefully().sync