之前寫了一篇文章:Java 網(wǎng)絡(luò)IO編程總結(jié)(BIO、NIO、AIO均含完整實(shí)例代碼),介紹了如何使用Java原生IO支持進(jìn)行網(wǎng)絡(luò)編程,本文介紹一種更為簡(jiǎn)單的方式,即Java NIO框架。
Netty是業(yè)界最流行的NIO框架之一,具有良好的健壯性、功能、性能、可定制性和可擴(kuò)展性。同時(shí),它提供的十分簡(jiǎn)單的API,大大簡(jiǎn)化了我們的網(wǎng)絡(luò)編程。
同Java IO介紹的文章一樣,本文所展示的例子,實(shí)現(xiàn)了一個(gè)相同的功能。
1、服務(wù)端
Server:
package com.anxpp.io.calculator.netty; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; public class Server { private int port; public Server(int port) { this.port = port; } public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ServerHandler()); } }); ChannelFuture f = b.bind(port).sync(); System.out.println("服務(wù)器開啟:"+port); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port; if (args.length > 0) { port = Integer.parseInt(args[0]); } else { port = 9090; } new Server(port).run(); } }
網(wǎng)頁題目:JavaNIO框架Netty簡(jiǎn)單使用的示例-創(chuàng)新互聯(lián)
標(biāo)題路徑:http://www.rwnh.cn/article34/iijpe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、網(wǎng)站內(nèi)鏈、自適應(yīng)網(wǎng)站、移動(dòng)網(wǎng)站建設(shè)、響應(yīng)式網(wǎng)站、做網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容