Java Code Examples for io.netty.bootstrap.ServerBootstrap#bind()

The following examples show how to use io.netty.bootstrap.ServerBootstrap#bind() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CustomProtocolServer.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

    EventLoopGroup bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
    EventLoopGroup workerGroup = new NioEventLoopGroup(workerGroupThreadCount);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new CustomProtocolInitializer(maxPayloadSize));
        ChannelFuture f = b.bind(PORT);
        f.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 2
Source File: JNettyDomainAcceptor.java    From Jupiter with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture bind(SocketAddress localAddress) {
    ServerBootstrap boot = bootstrap();

    initChannelFactory();

    boot.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(
                    new FlushConsolidationHandler(JConstants.EXPLICIT_FLUSH_AFTER_FLUSHES, true),
                    new IdleStateChecker(timer, JConstants.READER_IDLE_TIME_SECONDS, 0, 0),
                    idleStateTrigger,
                    CodecConfig.isCodecLowCopy() ? new LowCopyProtocolDecoder() : new ProtocolDecoder(),
                    encoder,
                    handler);
        }
    });

    setOptions();

    return boot.bind(localAddress);
}
 
Example 3
Source File: NettyWebsocketTtyBootstrap.java    From arthas with Apache License 2.0 6 votes vote down vote up
public void start(Consumer<TtyConnection> handler, final Consumer<Throwable> doneHandler) {
    group = new NioEventLoopGroup();

    ServerBootstrap b = new ServerBootstrap();
    b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new TtyServerInitializer(channelGroup, handler, workerGroup));

    final ChannelFuture f = b.bind(host, port);
    f.addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (future.isSuccess()) {
                channel = f.channel();
                doneHandler.accept(null);
            } else {
                doneHandler.accept(future.cause());
            }
        }
    });
}
 
Example 4
Source File: NettyWebsocketTtyBootstrap.java    From termd with Apache License 2.0 6 votes vote down vote up
public void start(Consumer<TtyConnection> handler, final Consumer<Throwable> doneHandler) {
  group = new NioEventLoopGroup();

  ServerBootstrap b = new ServerBootstrap();
  b.group(group)
      .channel(NioServerSocketChannel.class)
      .handler(new LoggingHandler(LogLevel.INFO))
      .childHandler(new TtyServerInitializer(channelGroup, handler, httpResourcePath));

  final ChannelFuture f = b.bind(host, port);
  f.addListener(new GenericFutureListener<Future<? super Void>>() {
    @Override
    public void operationComplete(Future<? super Void> future) throws Exception {
      if (future.isSuccess()) {
        channel = f.channel();
        doneHandler.accept(null);
      } else {
        doneHandler.accept(future.cause());
      }
    }
  });
}
 
Example 5
Source File: NettyServerServiceImpl.java    From sds with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void start() {
    bossGroup = new NioEventLoopGroup(); // (1)
    workerGroup = new NioEventLoopGroup();
    try {
        b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new SocketServerChannelInitializer(socketConfig.getHeartTime(),socketService,applicationContext));
        // Bind and start to accept incoming connections.
        b.bind(socketConfig.getPort());

        logger.info("socket: "+socketConfig.getPort()+" starting....");
        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 6
Source File: NettyServerServiceImpl.java    From Lottor with MIT License 6 votes vote down vote up
/**
 * 启动netty服务
 */
@Override
public void start() {
    SocketManager.getInstance().setMaxConnection(nettyConfig.getMaxConnection());
    servletExecutor = new DefaultEventExecutorGroup(MAX_THREADS);
    if (nettyConfig.getMaxThreads() != 0) {
        MAX_THREADS = nettyConfig.getMaxThreads();
    }
    try {
        final SerializeProtocolEnum serializeProtocolEnum =
                SerializeProtocolEnum.acquireSerializeProtocol(nettyConfig.getSerialize());

        nettyServerHandlerInitializer.setSerializeProtocolEnum(serializeProtocolEnum);
        nettyServerHandlerInitializer.setServletExecutor(servletExecutor);
        ServerBootstrap b = new ServerBootstrap();
        groups(b, MAX_THREADS << 1);
        b.bind(nettyConfig.getPort());

        LOGGER.info("netty service started on port: " + nettyConfig.getPort());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 7
Source File: OioEventLoopTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTooManyAcceptedChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    assertThat(s.getInputStream().read(), is(-1));
    s.close();

    g.shutdownGracefully();
}
 
Example 8
Source File: JNettyTcpAcceptor.java    From Jupiter with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture bind(SocketAddress localAddress) {
    ServerBootstrap boot = bootstrap();

    initChannelFactory();

    boot.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(
                    new FlushConsolidationHandler(JConstants.EXPLICIT_FLUSH_AFTER_FLUSHES, true),
                    new IdleStateChecker(timer, JConstants.READER_IDLE_TIME_SECONDS, 0, 0),
                    idleStateTrigger,
                    CodecConfig.isCodecLowCopy() ? new LowCopyProtocolDecoder() : new ProtocolDecoder(),
                    encoder,
                    handler);
        }
    });

    setOptions();

    return boot.bind(localAddress);
}
 
Example 9
Source File: PCEPDispatcherImpl.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public final synchronized ChannelFuture createServer(final PCEPDispatcherDependencies dispatcherDependencies) {
    this.keys = dispatcherDependencies.getKeys();

    final ChannelPipelineInitializer initializer = (ch, promise) -> {
        ch.pipeline().addLast(this.hf.getDecoders());
        ch.pipeline().addLast("negotiator", this.snf
                .getSessionNegotiator(dispatcherDependencies, ch, promise));
        ch.pipeline().addLast(this.hf.getEncoders());
    };

    final ServerBootstrap b = createServerBootstrap(initializer);
    final InetSocketAddress address = dispatcherDependencies.getAddress();
    final ChannelFuture f = b.bind(address);
    LOG.debug("Initiated server {} at {}.", f, address);

    this.keys = KeyMapping.getKeyMapping();
    return f;
}
 
Example 10
Source File: IOTGatewayServer.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

    EventLoopGroup bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
    EventLoopGroup workerGroup = new NioEventLoopGroup(workerGroupThreadCount);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new GatewayTransportServerInitializer(maxPayloadSize));
        ChannelFuture f = b.bind(PORT);
        f.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 11
Source File: NettyHomekitHttpService.java    From HAP-Java with MIT License 5 votes vote down vote up
public CompletableFuture<Integer> create(HomekitClientConnectionFactory connectionFactory) {
  final CompletableFuture<Integer> portFuture = new CompletableFuture<Integer>();
  ServerBootstrap b = new ServerBootstrap();
  b.group(bossGroup, workerGroup)
      .channel(NioServerSocketChannel.class)
      .handler(new LoggingHandler(LogLevel.INFO))
      .childHandler(new ServerInitializer(connectionFactory, allChannels, nThreads))
      .option(ChannelOption.SO_BACKLOG, 128)
      .childOption(ChannelOption.SO_KEEPALIVE, true);
  final ChannelFuture bindFuture = b.bind(localAddress, port);
  bindFuture.addListener(
      new GenericFutureListener<Future<? super Void>>() {

        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
          try {
            future.get();
            SocketAddress socketAddress = bindFuture.channel().localAddress();
            if (socketAddress instanceof InetSocketAddress) {
              logger.trace("Bound homekit listener to " + socketAddress.toString());
              portFuture.complete(((InetSocketAddress) socketAddress).getPort());
            } else {
              throw new RuntimeException(
                  "Unknown socket address type: " + socketAddress.getClass().getName());
            }
          } catch (Exception e) {
            portFuture.completeExceptionally(e);
          }
        }
      });
  return portFuture;
}
 
Example 12
Source File: BGPDispatcherImpl.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public synchronized ChannelFuture createServer(final InetSocketAddress serverAddress) {
    final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(this.bgpPeerRegistry);
    final ChannelPipelineInitializer<?> initializer = BGPChannel.createChannelPipelineInitializer(
        this.handlerFactory, snf);
    final ServerBootstrap serverBootstrap = createServerBootstrap(initializer);
    final ChannelFuture channelFuture = serverBootstrap.bind(serverAddress);
    LOG.debug("Initiated server {} at {}.", channelFuture, serverAddress);
    return channelFuture;
}
 
Example 13
Source File: OioEventLoopTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testTooManyClientChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Bootstrap cb = new Bootstrap();
    cb.channel(OioSocketChannel.class);
    cb.group(g);
    cb.handler(new ChannelInboundHandlerAdapter());
    ChannelFuture f2 = cb.connect(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    f2.await();

    assertThat(f2.cause(), is(instanceOf(ChannelException.class)));
    assertThat(f2.cause().getMessage().toLowerCase(), containsString("too many channels"));

    final CountDownLatch notified = new CountDownLatch(1);
    f2.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            notified.countDown();
        }
    });

    notified.await();
    g.shutdownGracefully();
}
 
Example 14
Source File: NettyServer.java    From hermes with Apache License 2.0 5 votes vote down vote up
public ChannelFuture start(int port) {
	ServerBootstrap b = new ServerBootstrap();
	b.group(m_bossGroup, m_workerGroup)//
	      .channel(NioServerSocketChannel.class)//
	      .childHandler(new ChannelInitializer<SocketChannel>() {
		      @Override
		      public void initChannel(SocketChannel ch) throws Exception {
			      ch.pipeline().addLast(
			            new DefaultNettyChannelOutboundHandler(),//
			            new NettyDecoder(), //
			            new MagicNumberAndLengthPrepender(), //
			            new NettyEncoder(), //
			            new IdleStateHandler(0, 0, m_config.getClientMaxIdleSeconds()),//
			            new DefaultServerChannelInboundHandler(lookup(CommandProcessorManager.class), m_config
			                  .getClientMaxIdleSeconds()));
		      }
	      }).option(ChannelOption.SO_BACKLOG, 128) // TODO set tcp options
	      .childOption(ChannelOption.SO_KEEPALIVE, true)//
	      .childOption(ChannelOption.SO_REUSEADDR, true)//
	      .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
	      .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024)//
	      .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024)//
	;

	// Bind and start to accept incoming connections.
	ChannelFuture f = b.bind(port);

	return f;
}
 
Example 15
Source File: HttpServer.java    From litchi with Apache License 2.0 5 votes vote down vote up
@Override
public void afterStart() {
    try {
        if (handlerList.isEmpty()) {
            throw new Exception("ChannelHandler is null");
        }

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
                .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                .option(ChannelOption.SO_BACKLOG, 12000).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline()
                                .addLast(new HttpServerCodec())
                                .addLast("aggregator", new HttpObjectAggregator(maxContentLength));
                        for (ChannelHandler handler : handlerList) {
                            ch.pipeline().addLast(handler);
                        }
                    }
                });

        b.bind(port);
        LOGGER.info("-----> connector started: http://127.0.0.1:{}/", port);
    } catch (Exception e) {
        LOGGER.error("{}", e);
    }
}
 
Example 16
Source File: ProxyServer.java    From waltz with Apache License 2.0 5 votes vote down vote up
public ProxyServer(int localPort, String remoteHost, int remotePort) throws UnknownHostException {
    this.remoteHost = remoteHost;
    this.remotePort = remotePort;
    this.bossGroup = new NioEventLoopGroup(1);
    this.workerGroup = new NioEventLoopGroup();

    ServerBootstrap b = new ServerBootstrap();
    b.group(this.bossGroup, this.workerGroup)
        .channel(NioServerSocketChannel.class)
        .childHandler(new ProxyServerInitializer())
        .childOption(ChannelOption.AUTO_READ, false);

    this.channelFuture = b.bind(InetAddress.getLocalHost(), localPort);
    this.channelFuture.awaitUninterruptibly();
}
 
Example 17
Source File: EchoServerWithFuture.java    From netty.book.kor with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new EchoServerHandlerWithFuture());
            }
        });

        ChannelFuture bindFuture = b.bind(8888);
        System.out.println("Bind 시작.");
        bindFuture.sync();
        System.out.println("Bind 완료.");

        Channel serverChannel = bindFuture.channel();
        ChannelFuture closeFuture = serverChannel.closeFuture();
        closeFuture.sync();
    }
    finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
 
Example 18
Source File: ShutdownRequestMonitor.java    From hermes with Apache License 2.0 5 votes vote down vote up
public void start() {
	ServerBootstrap b = new ServerBootstrap();

	b.group(m_bossGroup, m_workerGroup)//
	      .channel(NioServerSocketChannel.class)//
	      .childHandler(new ChannelInitializer<SocketChannel>() {
		      @Override
		      public void initChannel(SocketChannel ch) throws Exception {
			      ch.pipeline().addLast(new LineBasedFrameDecoder(10),//
			            new StringDecoder(Charsets.UTF_8),//
			            new IdleStateHandler(0, 0, MAX_IDLE_SECONDS),//
			            new ShutdownRequestInboundHandler());
		      }
	      }).option(ChannelOption.SO_BACKLOG, 128) // TODO set tcp options
	      .childOption(ChannelOption.SO_KEEPALIVE, true);

	// Bind and start to accept incoming connections.
	ChannelFuture f = b.bind(m_config.getShutdownRequestPort());

	f.addListener(new ChannelFutureListener() {

		@Override
		public void operationComplete(ChannelFuture future) throws Exception {
			if (future.isSuccess()) {
				log.info("Broker shutdown port is {}.", m_config.getShutdownRequestPort());
			} else {
				log.error("Failed to listen shutdown port {}.", m_config.getShutdownRequestPort());
			}

		}
	});
}
 
Example 19
Source File: EchoServerWS.java    From examples-javafx-repos1 with Apache License 2.0 5 votes vote down vote up
public ChannelFuture start(InetSocketAddress address) {

	ServerBootstrap bootstrap = new ServerBootstrap();
	bootstrap
		.group(group)
		.channel(NioServerSocketChannel.class)
		.childHandler(createInitializer());
	
	ChannelFuture future = bootstrap.bind(address);
	future.syncUninterruptibly();
	channel = future.channel();

	return future;
}
 
Example 20
Source File: ChatServer.java    From netty-learning with MIT License 5 votes vote down vote up
private ChannelFuture start() {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(group)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChatServerInitializer(channelGroup,sslContext)) ;

    ChannelFuture future = bootstrap.bind(new InetSocketAddress(PORT));

    //同步
    future.syncUninterruptibly();
    channel = future.channel() ;
    return future ;
}