LineBaseEchoServer

  1. public class LineBaseEchoServer {
  2. public static final int PORT = 9998;
  3. public static void main(String[] args) throws InterruptedException {
  4. LineBaseEchoServer lineBaseEchoServer = new LineBaseEchoServer();
  5. System.out.println("服务器即将启动");
  6. lineBaseEchoServer.start();
  7. }
  8. public void start() throws InterruptedException {
  9. final LineBaseServerHandler serverHandler = new LineBaseServerHandler();
  10. EventLoopGroup group = new NioEventLoopGroup();/*线程组*/
  11. try {
  12. ServerBootstrap b = new ServerBootstrap();/*服务端启动必须*/
  13. b.group(group)/*将线程组传入*/
  14. .channel(NioServerSocketChannel.class)/*指定使用NIO进行网络传输*/
  15. .localAddress(new InetSocketAddress(PORT))/*指定服务器监听端口*/
  16. /*服务端每接收到一个连接请求,就会新启一个socket通信,也就是channel,
  17. 所以下面这段代码的作用就是为这个子channel增加handle*/
  18. .childHandler(new ChannelInitializerImp());
  19. ChannelFuture f = b.bind().sync();/*异步绑定到服务器,sync()会阻塞直到完成*/
  20. System.out.println("服务器启动完成,等待客户端的连接和数据.....");
  21. f.channel().closeFuture().sync();/*阻塞直到服务器的channel关闭*/
  22. } finally {
  23. group.shutdownGracefully().sync();/*优雅关闭线程组*/
  24. }
  25. }
  26. private static class ChannelInitializerImp extends ChannelInitializer<Channel> {
  27. @Override
  28. protected void initChannel(Channel ch) throws Exception {
  29. ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
  30. ch.pipeline().addLast(new LineBaseServerHandler());
  31. }
  32. }
  33. }