關於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().