Netty Server Demo 发表于 2018-12-14Maven添加依赖12345<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.29.Final</version></dependency>Server Demo模拟请求/响应model123456789101112131415161718192021222324package com.zsr.test.netty;public class RequestData { private int intValue; public int getIntValue() { return intValue; } public void setIntValue(int intValue) { this.intValue = intValue; }}// return RequestData inValue * 2public class ResponseData { private int intValue; public int getIntValue() { return intValue; } public void setIntValue(int intValue) { this.intValue = intValue; }}服务端对请求解码12345678public class ServerRequestDecoder extends ReplayingDecoder<RequestData> { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { RequestData data = new RequestData(); data.setIntValue(in.readInt()); out.add(data); }}服务端对响应编码123456public class ServerResponseEncoder extends MessageToByteEncoder<ResponseData> { @Override protected void encode(ChannelHandlerContext ctx, ResponseData msg, ByteBuf out) throws Exception { out.writeInt(msg.getIntValue()); }}服务端具体业务处理12345678910public class ServerProcessingHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { RequestData requestData = (RequestData) msg; ResponseData responseData = new ResponseData(); responseData.setIntValue(requestData.getIntValue() * 2); ctx.writeAndFlush(responseData); System.out.println("server receive request: " + requestData.getIntValue()); }}启动服务12345678910111213141516171819202122232425262728293031public class NettyTestServer { public static void main(String[] args) throws Exception { new NettyTestServer(8080).start(); } public void start() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ServerRequestDecoder(), new ServerResponseEncoder(), new ServerProcessingHandler()); } }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(port)).sync(); System.out.println( NettyTestServer.class.getName() + " started and listen on " + channelFuture.channel().localAddress()); channelFuture.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }}参考Introduction to NettyNetty的那点事儿