1. 老规矩, 引入我们喜闻乐见的maven依赖
1 <dependency> 2 <groupId>io.netty</groupId> 3 <artifactId>netty-all</artifactId> 4 <version>4.1.6.Final</version> 5 </dependency>
2. 服务端
2.1: 服务端引导类:
1 public class EchoServer { 2 3 private int port; 4 5 private EchoServer(int port) { 6 this.port = port; 7 } 8 9 private void start() throws Exception { 10 System.out.println("Echo Server Start"); 11 EventLoopGroup group = new NioEventLoopGroup(); 12 try { 13 ServerBootstrap b = new ServerBootstrap(); 14 b.group(group) 15 .channel(NioServerSocketChannel.class) 16 .localAddress(new InetSocketAddress(port)) 17 .childHandler(new ChannelInitializer<SocketChannel>() { 18 @Override 19 public void initChannel(SocketChannel ch) throws Exception { 20 ch.pipeline().addLast(new EchoOutboundHandler1()); 21 ch.pipeline().addLast(new EchoOutboundHandler2()); 22 23 ch.pipeline().addLast(new EchoInboundHandler1()); 24 ch.pipeline().addLast(new EchoInboundHandler2()); 25 } 26 }); 27 ChannelFuture f = b.bind().sync(); 28 System.out.println("Server Start Listen At: " + port); 29 f.channel().closeFuture().sync(); 30 } finally { 31 group.shutdownGracefully();