標籤:style http ar io os 使用 sp java strong
Netty官網:http://netty.io/
本常式使用最新的netty5.x版本編寫
伺服器端:
TimeServer 時間伺服器 服務端接收用戶端的串連請求和查詢目前時間的指令,判斷指令正確後響應返回當前伺服器的校準時間。
package c1;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;/** * server 有粘包問題 * @author xwalker */public class TimeServer {public void bind(int port) throws Exception {// 伺服器線程組 用於網路事件的處理 一個用於伺服器接收用戶端的串連// 另一個線程組用於處理SocketChannel的網路讀寫EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try {// NIO伺服器端的輔助啟動類 降低伺服器開發難度ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)// 類似NIO中serverSocketChannel.option(ChannelOption.SO_BACKLOG, 1024)// 配置TCP參數.childHandler(new ChildChannelHandler());// 最後綁定I/O事件的處理類// 處理網路IO事件// 伺服器啟動後 綁定監聽連接埠 同步等待成功 主要用於非同步作業的通知回調 回調處理用的ChildChannelHandlerChannelFuture f = serverBootstrap.bind(port).sync();System.out.println("timeServer啟動");// 等待服務端監聽連接埠關閉f.channel().closeFuture().sync();} finally {// 優雅退出 釋放線程池資源bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();System.out.println("伺服器優雅的釋放了線程資源...");}}/** * 網路事件處理器 */private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(new TimeServerHandler());}}public static void main(String[] args) throws Exception {int port = 8000;new TimeServer().bind(port);}}
TimerServer接收到用戶端的串連和讀寫請求後交給處理器handler進行事件的響應處理,伺服器定義兩組線程組,一組用來處理用戶端串連,一組用來處理網路IO事件(SocketChannel)的響應,NioEventLoopGroup是Netty提供的NIO線程組,實際上就是Java NIO中的Reactor線程組。
ServerBootstrap是Netty提供的用於NIO服務端輔助啟動類,降低了NIO服務端的開發複雜度。
ServerBootstrap需要綁定伺服器網路IO事件的處理類ChildChannelHandler ,用於實際處理具體的IO事件,例如記錄日誌,對訊息編解碼等。
TimeServerHandler需要繼承Netty提供的適配器ChannelhandlerAdapter重寫channelRead等方法完成訊息的讀寫。
package c1;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;import java.util.Date;/** * server端網路IO事件處理 * @author xwalker * */public class TimeServerHandler extends ChannelHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {System.out.println("伺服器讀取到用戶端請求...");ByteBuf buf=(ByteBuf) msg;byte[] req=new byte[buf.readableBytes()];buf.readBytes(req);String body=new String(req,"UTF-8");System.out.println("the time server receive order:"+body);String curentTime="QUERY TIME ORDER".equalsIgnoreCase(body)?new Date(System.currentTimeMillis()).toString():"BAD ORDER";ByteBuf resp=Unpooled.copiedBuffer(curentTime.getBytes());ctx.write(resp);System.out.println("伺服器做出了響應");}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.flush();System.out.println("伺服器readComplete 響應完成");}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {ctx.close();System.out.println("伺服器異常退出"+cause.getMessage());}}
伺服器通過handler接收和處理訊息請求,channelRead中的msg就是用戶端請求的訊息,通過解碼擷取具體資訊後根據訊息格式和定義完成後續的響應。
ByteBuf是netty封裝和擴充的java NIO中的ByteBuffer類,功能更完善。通過ByteBuf接收和解碼msg 轉成String類型 然後判斷命令是都準確,根據結果做出響應。
用戶端:
用戶端的處理比較簡單,啟動用戶端,連結的伺服器成功後發送時間查詢的指令,等待伺服器響應。
package c1;import io.netty.bootstrap.Bootstrap;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.NioSocketChannel;/** * client 存在TCP粘包問題 * @author xwlaker * */public class TimeClient {/** * 串連伺服器 * @param port * @param host * @throws Exception */public void connect(int port, String host) throws Exception {//配置用戶端NIO線程組EventLoopGroup group = new NioEventLoopGroup();try {//用戶端輔助啟動類 對用戶端配置Bootstrap b = new Bootstrap();b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch)throws Exception {ch.pipeline().addLast(new TimeClientHandler());}});//非同步連結的伺服器 同步等待連結成功ChannelFuture f = b.connect(host, port).sync();//等待連結關閉f.channel().closeFuture().sync();} finally {group.shutdownGracefully();System.out.println("用戶端優雅的釋放了線程資源...");}}public static void main(String[] args) throws Exception {new TimeClient().connect(8000, "127.0.0.1");}}
用戶端定義一組線程組用於處理與伺服器的網路IO事件。通過用戶端輔助啟動類 Bootstrap來配置線程組、TCP參數以及IO事件處理的Handler。
package c1;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;import java.util.logging.Logger;/** * Client 網路IO事件處理 * @author xwalker * */public class TimeClientHandler extends ChannelHandlerAdapter {private static final Logger logger=Logger.getLogger(TimeClientHandler.class.getName());private ByteBuf firstMessage;public TimeClientHandler(){byte[] req ="QUERY TIME ORDER".getBytes();firstMessage=Unpooled.buffer(req.length);firstMessage.writeBytes(req);}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {ctx.writeAndFlush(firstMessage);System.out.println("用戶端active");}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {System.out.println("用戶端收到伺服器響應資料");ByteBuf buf=(ByteBuf) msg;byte[] req=new byte[buf.readableBytes()];buf.readBytes(req);String body=new String(req,"UTF-8");System.out.println("Now is:"+body);}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.flush();System.out.println("用戶端收到伺服器響應資料處理完成");}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {logger.warning("Unexpected exception from downstream:"+cause.getMessage());ctx.close();System.out.println("用戶端異常退出");}}
TimeClienthandler繼承Netty提供的Handler適配器,重寫channelActive和channelRead方法 前者通道開啟active狀態時 發送查詢指令,後者接收伺服器響應的訊息並解碼輸出。
運行結果:
用戶端啟動後首先處理器channelActive被調用發送查詢指令,伺服器端接收到查詢指令後返回了目前時間,用戶端接收到伺服器響應後解碼輸出目前時間。
Netty5入門學習筆記001