Netty的socket編程(四)

來源:互聯網
上載者:User

標籤:put   bootstrap   net   handle   active   final   tin   rup   write   

Netty提供的handler:編解碼,訊息頭,訊息編碼

 

1. 串連建立後,用戶端和服務端都不會主動發訊息,實現handler的channelActive來觸發訊息發送。

2.SimpleChannelInboundHandler的重載方法

(1)handlerAdded  串連建立時調用

(2)HandlerRemoved 串連斷開時調用

(3)HandlerActive 串連處於活動狀態調用

(4)HandlerInactive 串連處於不活動狀態調用

 

socket樣本 :

server啟動類:

 

 1 public class MyServer { 2  3     public static void main(String[] args) throws InterruptedException { 4  5         EventLoopGroup bossGroup = new NioEventLoopGroup(); 6         EventLoopGroup workerGroup = new NioEventLoopGroup(); 7  8         try{ 9             ServerBootstrap serverBootstrap = new ServerBootstrap();10             serverBootstrap.group(bossGroup,workerGroup).11                     channel(NioServerSocketChannel.class)12                     .childHandler(new MyServerInitializer());13             ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();14             channelFuture.channel().closeFuture().sync();15 16         }finally {17 18             bossGroup.shutdownGracefully();19             workerGroup.shutdownGracefully();20 21         }22 23     }24 25 }

 

 

server初始化類 :

 1 public class MyServerInitializer  extends ChannelInitializer<SocketChannel>{ 2  3  4     @Override 5     protected void initChannel(SocketChannel ch) throws Exception { 6  7         ChannelPipeline channelPipeline = ch.pipeline(); 8  9         //解碼器10         channelPipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));11         //訊息 加header12         channelPipeline.addLast(new LengthFieldPrepender(4));13         channelPipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));14         channelPipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));15         channelPipeline.addLast(new MyServerHandler());16 17     }18 }

 

server業務處理handler:

 1 public class MyServerHandler extends SimpleChannelInboundHandler<String> { 2     @Override 3     protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { 4  5         System.out.println(ctx.channel().remoteAddress()+"msg:"+msg); 6  7         ctx.channel().writeAndFlush("from server "+ UUID.randomUUID()); 8  9     }10 11     @Override12     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {13         cause.printStackTrace();14         ctx.close();15     }16 }

 

 

client 類

client啟動類:

 1 public class MyClient { 2  3     public static void main(String[] args) throws InterruptedException { 4  5         EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); 6  7         try{ 8             Bootstrap bootstrap = new Bootstrap(); 9             bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)10                     .handler(new MyClientInitializer());11 12             ChannelFuture channelFuture = bootstrap.connect("localhost",8899).sync();13             channelFuture.channel().closeFuture().sync();14         }finally {15             eventLoopGroup.shutdownGracefully();16         }17 18 19     }20 21 }

 

client初始化類 : 

 

 1 public class MyClientInitializer extends ChannelInitializer<SocketChannel>{ 2     @Override 3     protected void initChannel(SocketChannel ch) throws Exception { 4         ChannelPipeline channelPipeline = ch.pipeline(); 5         //解碼器 6         channelPipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4)); 7         //訊息 加header 8         channelPipeline.addLast(new LengthFieldPrepender(4)); 9         channelPipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));10         channelPipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));11         channelPipeline.addLast(new MyClientHandler());  //自己的處理器12     }13 }

 

client業務處理handler :

 

 1 public class MyClientHandler extends SimpleChannelInboundHandler<String>{ 2     @Override 3     protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { 4         System.out.println(ctx.channel().remoteAddress()); 5         System.out.println("client output "+msg); 6         ctx.writeAndFlush("from client "+ LocalDateTime.now()); 7  8     } 9 10     @Override11     public void channelActive(ChannelHandlerContext ctx) throws Exception {12         ctx.writeAndFlush("來自用戶端的問候!!");13     }14 15     @Override16     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {17         cause.printStackTrace();18         ctx.close();19     }20 }

 

Netty的socket編程(四)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.