|
| 1 | +package cn.aofeng.demo.netty40x.echo; |
| 2 | + |
| 3 | +import io.netty.bootstrap.ServerBootstrap; |
| 4 | +import io.netty.channel.ChannelFuture; |
| 5 | +import io.netty.channel.ChannelOption; |
| 6 | +import io.netty.channel.EventLoopGroup; |
| 7 | +import io.netty.channel.nio.NioEventLoopGroup; |
| 8 | +import io.netty.channel.socket.nio.NioServerSocketChannel; |
| 9 | + |
| 10 | +import org.apache.commons.lang.math.NumberUtils; |
| 11 | +import org.apache.log4j.Logger; |
| 12 | + |
| 13 | +/** |
| 14 | + * Echo服务端:将客户端发送的请求原样返回。 |
| 15 | + * |
| 16 | + * @author <a href="mailto:[email protected]">聂勇</a> |
| 17 | + */ |
| 18 | +public class EchoServer { |
| 19 | + |
| 20 | + private static Logger _logger = Logger.getLogger(EchoServer.class); |
| 21 | + |
| 22 | + public void start(int port) { |
| 23 | + EventLoopGroup boss = new NioEventLoopGroup(1); |
| 24 | + EventLoopGroup worker = new NioEventLoopGroup(10); |
| 25 | + ServerBootstrap bootstrap = new ServerBootstrap(); |
| 26 | + try { |
| 27 | + bootstrap.group(boss, worker) |
| 28 | + .channel(NioServerSocketChannel.class) |
| 29 | + .option(ChannelOption.SO_BACKLOG, 128) |
| 30 | + .childHandler(new EchoServerHandler()) |
| 31 | + .localAddress(port); |
| 32 | + ChannelFuture bindFuture = bootstrap.bind().sync(); |
| 33 | + ChannelFuture closeFuture = bindFuture.channel().closeFuture().sync(); |
| 34 | + _logger.info( String.format("%s started and listen on %s", this.getClass().getSimpleName(), closeFuture ) ); |
| 35 | + } catch(Exception ex) { |
| 36 | + _logger.info( String.format("%s start failed", this.getClass().getSimpleName()), ex); |
| 37 | + } finally { |
| 38 | + boss.shutdownGracefully(); |
| 39 | + worker.shutdownGracefully(); |
| 40 | + } |
| 41 | + |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * @param args |
| 46 | + */ |
| 47 | + public static void main(String[] args) { |
| 48 | + if (args.length != 1) { |
| 49 | + _logger.error("Invalid arguments。Usage:/njava cn.aofeng.demo.netty40x.echo.EchoServer 8080"); |
| 50 | + System.exit(-1); |
| 51 | + } |
| 52 | + |
| 53 | + int port = NumberUtils.toInt(args[0], 8080); |
| 54 | + EchoServer server = new EchoServer(); |
| 55 | + server.start(port); |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments