Netty實戰-對象編解碼,Netty對象網路傳遞

來源:互聯網
上載者:User

標籤:netty實戰 解決tcp粘包

書籍推薦:

       執行個體代碼 : http://download.csdn.net/detail/jiangtao_st/7677503

  1. Server端代碼
    <span style="font-size:12px;">/** *  * <p> * Netty Server Simple * </p> *  * LineBasedFrameDecoder + 訊息中得分行符號 *  * @author 卓軒 * @建立時間:2014年7月7日 * @version: V1.0 */public class NettyServer {private final int port = 8989;@Testpublic void nettyServer(){EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChildChannelHandler());//綁定連接埠、同步等待ChannelFuture futrue = serverBootstrap.bind(port).sync();//等待服務監聽連接埠關閉futrue.channel().closeFuture().sync();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{//退出,釋放線程等相關資源bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{@Overrideprotected void initChannel(SocketChannel ch) throws Exception {//ch.pipeline().addLast(new LineBasedFrameDecoder(1024));////ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());//ch.pipeline().addLast(new DelimiterBasedFrameDecoder(2048, delimiter));////ch.pipeline().addLast(new FixedLengthFrameDecoder(20));ch.pipeline().addLast(new ObjectDecoder(1024*1024,ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));ch.pipeline().addLast(new ObjectEncoder());ch.pipeline().addLast(new StringDecoder());ch.pipeline().addLast(new UserRespServerHandler());}}}</span>
  2. Client端代碼
    <span style="font-size:12px;">/** *  * <p> * NettyClient  實現 * </p> *  * @author 卓軒 * @建立時間:2014年7月7日 * @version: V1.0 */public class NettyClient {public void connect(int port,String host){EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.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 ObjectDecoder(1024,ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));ch.pipeline().addLast(new ObjectEncoder());ch.pipeline().addLast(new StringDecoder());ch.pipeline().addLast(new UserQueryClientHandler());}});//發起非同步連結操作ChannelFuture channelFuture = bootstrap.connect(host, port).sync();channelFuture.channel().closeFuture().sync();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{//關閉,釋放線程資源group.shutdownGracefully();}}@Testpublic void nettyClient(){new NettyClient().connect(8989, "localhost");}}</span>
  3. ServerHander 代碼
    <span style="font-size:12px;">/** *  * <p> *  使用者查詢返回 * </p> *  * @author 卓軒 * @建立時間:2014年7月7日 * @version: V1.0 */public class UserRespServerHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {UserQuery userQuery = (UserQuery) msg;System.out.println("收到來自用戶端的查詢請求:"+ String.valueOf(userQuery));if(userQuery != null && userQuery.getUserId()!= 0){UserDO userDO = getUserById(userQuery.getUserId());ctx.writeAndFlush(userDO);}}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {System.out.println("Server has Exception,"+ cause.getCause());}private UserDO getUserById(int userId){if(userId % 2 == 0){UserDO zhuoxuan = new UserDO();zhuoxuan.setUserId(userId);zhuoxuan.setSex(1);zhuoxuan.setUname("卓軒");zhuoxuan.setUnick("zhuoxuan");zhuoxuan.setEmail("[email protected]");return zhuoxuan;}else{UserDO zhuoxuan = new UserDO();zhuoxuan.setUserId(userId);zhuoxuan.setSex(1);zhuoxuan.setUname("張三");zhuoxuan.setUnick("zhangsan");zhuoxuan.setEmail("[email protected]");return zhuoxuan;}}}</span><strong style="font-size: 14px;"></strong>

  4. ClientHander 代碼

<span style="font-size:12px;">/** *  * <p> * 使用者查詢請求 Handler * </p> *  * @author 卓軒 * @建立時間:2014年7月7日 * @version: V1.0 */public class UserQueryClientHandler extends ChannelInboundHandlerAdapter {public UserQueryClientHandler() {}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {for (int i = 0; i < 100; i++) {UserQuery userQuery = new UserQuery();userQuery.setUserId(1001+i);ctx.write(userQuery);}ctx.flush();}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {String message = String.valueOf(msg);System.out.println("Netty-Client:Receive Message,"+ message);}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.flush();}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {System.out.println("Client has Exception,"+ cause.getCause());}}</span>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.