NETTY实战

//TCP监听

public void run(){
  try {
   this.logger.info("监听TCP端口:" + String.valueOf(this.port));
   b.group(bossGroup, workerGroup)
   .channel(NioServerSocketChannel.class)
   .option(ChannelOption.SO_BACKLOG, 1000)
   .handler(new LoggingHandler(LogLevel.INFO))
   .childHandler(new ChannelInitializer<SocketChannel>(){
    @Override
    protected void initChannel(SocketChannel ch)
      throws Exception {
     ch.pipeline().addLast(new TCPChannelHandlerAdapter(port, logger));
    }
   });   
   b.bind(port).sync().channel().closeFuture().sync();   
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }
  finally{
   bossGroup.shutdownGracefully();
   workerGroup.shutdownGracefully();
  }

  }

 

 

//UDP监听

public void run()
 {
  //EventLoopGroup group = new NioEventLoopGroup();
        try {
            this.logger.info("监听UDP端口:" + String.valueOf(this.port));
            b.group(bossGroup)
             .channel(NioDatagramChannel.class)
             .option(ChannelOption.SO_BACKLOG, 1000)
             .option(ChannelOption.SO_BROADCAST, true)
             .handler(new UDPChannelHandlerAdapter(port,this.server, this.udpchannels));
            //System.out.println("UDP:"+port+" Server is starting……"); 
            b.bind(port).sync().channel().closeFuture().await();
          
        }
        catch (Exception e) {
         e.printStackTrace();
  }
        finally {
            bossGroup.shutdownGracefully();
        }

 }

你可能感兴趣的:(NETTY实战)