Java tutorial
/* * Copyright 2016 Zhongan.com All right reserved. This software is the * confidential and proprietary information of Zhongan.com ("Confidential * Information"). You shall not disclose such Confidential Information and shall * use it only in accordance with the terms of the license agreement you entered * into with Zhongan.com. */ package com.dingwang.netty.handler; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; /** * DiscardServerHandler.java??TODO ?? * * @author wangding_91@163.com 2016218 ?3:04:38 */ public class DiscardServerHandler extends ChannelHandlerAdapter { /* * (non-Javadoc) * @see io.netty.channel.ChannelHandlerAdapter#channelRead(io.netty.channel. * ChannelHandlerContext, java.lang.Object) */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // ByteBuf in = (ByteBuf) msg; // try { //??? // StringBuilder sb = new StringBuilder(); // while (in.isReadable()) { // sb.append((char) in.readByte()); // } // System.out.println(sb.toString()); // } catch (Exception e) { // ReferenceCountUtil.release(msg); // } //? //ctx.write(Object)????ctx.flush()?? //??cxt.writeAndFlush(msg)? System.out.println("server read" + msg.toString()); ctx.writeAndFlush(msg); } /* * (non-Javadoc) * @see * io.netty.channel.ChannelHandlerAdapter#exceptionCaught(io.netty.channel. * ChannelHandlerContext, java.lang.Throwable) */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } /* * (non-Javadoc) * @see * io.netty.channel.ChannelHandlerAdapter#channelActive(io.netty.channel. * ChannelHandlerContext) */ @Override //channelActive()?? //32?? public void channelActive(ChannelHandlerContext ctx) throws Exception { //????????32? //?4ByteBufChannelHandlerContext.alloc()?ByteBufAllocator //?? // final ByteBuf time = ctx.alloc().buffer(4); // time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L)); //???ChannelHandlerContext.write()( //writeAndFlush())ChannelFutureChannelFuture?I/O? //????Netty???? //????? //?write()ChannelFuture??close()???? //??,close()??ChannelFuture // final ChannelFuture f = ctx.writeAndFlush(time); //?????ChannelFuture //ChannelFutureListener??ChannelFutureListener??? //Channel????: //f.addListener(ChannelFutureListener.CLOSE); // f.addListener(new ChannelFutureListener() { // @Override // // public void operationComplete(ChannelFuture future) { // assert f == future; // ctx.close(); // // } // }); System.out.println("test idle"); ChannelFuture f = ctx.writeAndFlush("hhhh"); f.addListener(ChannelFutureListener.CLOSE); } }