test.proto文件
package protobuf; option java_package = "com.test.protobuf"; option java_outer_classname = "FirstProtobuf"; message testBuf { required int32 ID = 1; required string Url = 2; }
Server端代码:
package com.test.server; import com.sun.istack.internal.logging.Logger; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; public class TimeServer { private static final Logger logger = Logger.getLogger(TimeServer.class); private static final String IP = "127.0.0.1"; private static final int PORT = 9999; /** 用于分配处理业务线程的线程组个数 */ protected static final int BIZGROUPSIZE = Runtime.getRuntime() .availableProcessors() * 2; // 默认 /** 业务出现线程大小 */ protected static final int BIZTHREADSIZE = 4; private static final EventLoopGroup bossGroup = new NioEventLoopGroup( BIZGROUPSIZE); private static final EventLoopGroup workerGroup = new NioEventLoopGroup( BIZTHREADSIZE); protected static void run() throws Exception { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.childHandler(new TimeServerInitializer()); b.bind(IP, PORT).sync(); logger.info("TCP服务器已启动"); } protected static void shutdown() { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } public static void main(String[] args) throws Exception { logger.info("开始启动TCP服务器..."); TimeServer.run(); // TcpServer.shutdown(); } }server Initializer
package com.test.server; import com.test.protobuf.FirstProtobuf; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.codec.protobuf.ProtobufDecoder; import io.netty.handler.codec.protobuf.ProtobufEncoder; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; public class TimeServerInitializer extends ChannelInitializer<SocketChannel>{ @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); pipeline.addLast("encoder",new ProtobufEncoder()); pipeline.addLast("decoder", new ProtobufDecoder(FirstProtobuf.testBuf.getDefaultInstance())); pipeline.addLast(new TimeServerHandler()); } }
server handler:
package com.test.server; import java.util.Date; import com.sun.istack.internal.logging.Logger; import com.test.protobuf.FirstProtobuf; import com.test.protobuf.FirstProtobuf.testBuf; import sun.awt.im.SimpleInputMethodWindow; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.ChannelHandler.Sharable; @Sharable public class TimeServerHandler extends SimpleChannelInboundHandler<FirstProtobuf.testBuf>{ //private int counter; private static final Logger logger = Logger.getLogger(TimeServerHandler.class); @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { //cause.printStackTrace(); ctx.close(); } @Override protected void channelRead0(ChannelHandlerContext ctx, testBuf msg) throws Exception { System.out.println("server:" + "channelRead:" + msg.getUrl()); FirstProtobuf.testBuf.Builder builder = FirstProtobuf.testBuf.newBuilder(); builder.setID(1); builder.setUrl("welcome"); ctx.writeAndFlush(builder.build()); } }
Client端代码:
package com.test.client; import com.sun.istack.internal.logging.Logger; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; public class TimeClient { private static final Logger logger = Logger.getLogger(TimeClient.class); public static String HOST = "127.0.0.1"; public static int PORT = 9999; //public static Bootstrap bootstrap = getBootstrap(); //public static Channel channel = getChannel(HOST, PORT); /** * 初始化Bootstrap * * @return * @throws InterruptedException */ public void run() throws InterruptedException { EventLoopGroup group = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class); b.handler(new TimeClientInitializer()); //b.option(ChannelOption.SO_KEEPALIVE, true); b.connect(HOST, PORT).sync(); } public static void main(String[] args) throws Exception { new TimeClient().run(); } }
client Initializer
package com.test.client; import com.test.protobuf.FirstProtobuf; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.codec.protobuf.ProtobufDecoder; import io.netty.handler.codec.protobuf.ProtobufEncoder; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; public class TimeClientInitializer extends ChannelInitializer<SocketChannel>{ @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); pipeline.addLast("encoder",new ProtobufEncoder()); pipeline.addLast("decoder", new ProtobufDecoder(FirstProtobuf.testBuf.getDefaultInstance())); pipeline.addLast(new TimeClientHandler()); } }
client handler:
package com.test.client; import com.sun.istack.internal.logging.Logger; import com.test.protobuf.FirstProtobuf; import com.test.protobuf.FirstProtobuf.testBuf; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.SimpleChannelInboundHandler; public class TimeClientHandler extends SimpleChannelInboundHandler<FirstProtobuf.testBuf>{ private static final Logger logger = Logger.getLogger(TimeClientHandler.class); private int counter; private FirstProtobuf.testBuf.Builder builder = FirstProtobuf.testBuf.newBuilder(); public TimeClientHandler(){ builder.setID(1); builder.setUrl("www.baidu.com"); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { //ByteBuf message = null; for(int i = 0;i<100;i++){ ctx.channel().writeAndFlush(builder.build()); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.warning("Unexpected exception from downstream:"+ cause.getMessage()); ctx.close(); } /*@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { String body = (String) msg; System.out.println("Now is:"+body+";the counter is :" + ++counter); }*/ @Override protected void channelRead0(ChannelHandlerContext ctx, testBuf msg) throws Exception { System.out.println(msg.getID()+" "+msg.getUrl()); } }