List of usage examples for io.netty.bootstrap ServerBootstrap childHandler
ChannelHandler childHandler
To view the source code for io.netty.bootstrap ServerBootstrap childHandler.
Click Source Link
From source file:example.http.upload.HttpUploadServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/* www . j a va 2 s.c o m*/ SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.handler(new LoggingHandler(LogLevel.INFO)); b.childHandler(new HttpUploadServerInitializer(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); System.err.println("Open your web browser and navigate to " + (SSL ? "https" : "example/http") + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:fr.letroll.ttorrentandroid.client.io.PeerServer.java
License:Apache License
public void start() throws Exception { group = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(group);// ww w . j ava 2s . c om b.channel(NioServerSocketChannel.class); b.option(ChannelOption.SO_BACKLOG, 128); b.option(ChannelOption.SO_REUSEADDR, true); b.option(ChannelOption.TCP_NODELAY, true); b.childHandler(new PeerServerHandshakeHandler(client)); b.childOption(ChannelOption.SO_KEEPALIVE, true); // b.childOption(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES)); if (address != null) { future = b.bind(address).sync(); } else { BIND: { Exception x = new IOException("No available port for the BitTorrent client!"); for (int i = PORT_RANGE_START; i <= PORT_RANGE_END; i++) { try { future = b.bind(i).sync(); break BIND; } catch (InterruptedException e) { throw e; } catch (Exception e) { x = e; } } throw new IOException("Failed to find an address to bind in range [" + PORT_RANGE_START + "," + PORT_RANGE_END + "]", x); } } }
From source file:gwlpr.loginshard.LoginShardFactory.java
License:Open Source License
@Override public Channel getServerChannel(ServerBootstrap bootstrap) throws InterruptedException { // set the attributes for new channels bootstrap.childAttr(ClientBean.HANDLE_KEY, null); // create the pipeline-factory bootstrap.childHandler(new LoginShardChannelInitializer(EncryptionOptions.Enable)); // finally, bind and sync return bootstrap.bind(8112).sync().channel(); }
From source file:gwlpr.mapshard.MapShardFactory.java
License:Open Source License
@Override public Channel getServerChannel(ServerBootstrap bootstrap) throws InterruptedException { // set the attributes for new channels bootstrap.childAttr(ClientBean.HANDLE_KEY, null); // create the pipeline-factory bootstrap.childHandler(new MapShardChannelInitializer(EncryptionOptions.Enable)); // finally, bind and sync return bootstrap.bind(9112).sync().channel(); }
From source file:hivemall.mix.server.MixServer.java
License:Open Source License
private void acceptConnections(@Nonnull MixServerInitializer initializer, int port) throws InterruptedException { final EventLoopGroup bossGroup = new NioEventLoopGroup(1); final EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from w w w . j a va2s. co m*/ ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_KEEPALIVE, true); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.handler(new LoggingHandler(LogLevel.INFO)); b.childHandler(initializer); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(port).sync(); this.state = ServerState.RUNNING; // Wait until the server socket is closed. // In this example, this does not happen, but you can do that to gracefully // shut down your server. f.channel().closeFuture().sync(); } finally { this.state = ServerState.STOPPING; workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
From source file:holon.internal.http.netty.NettyEngine.java
License:Open Source License
@Override public void serve(Supplier<Iterable<Route>> routes) { running = true;// www.j a v a 2 s.c o m executor = Executors.newCachedThreadPool(); disruptor = new Disruptor<>(NettyWorkEvent::new, 1024, executor); disruptor.handleEventsWithWorkerPool(createWorkers(workers, routes)); disruptor.start(); RingBuffer<NettyWorkEvent> ringBuffer = disruptor.getRingBuffer(); bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.childHandler(new Initializer(ringBuffer)); try { b.bind(httpPort).sync(); } catch (InterruptedException e) { throw new HolonException("Failed to bind to '" + httpPort + "', " + e.getMessage()); } }
From source file:io.advantageous.conekt.http.impl.HttpServerImpl.java
License:Open Source License
public synchronized HttpServer listen(int port, String host, Handler<AsyncResult<HttpServer>> listenHandler) { if (requestStream.handler() == null && wsStream.handler() == null) { throw new IllegalStateException("Set request or websocket handler first"); }/*from w ww . ja v a 2s .co m*/ if (listening) { throw new IllegalStateException("Already listening"); } listenContext = vertx.getOrCreateContext(); listening = true; serverOrigin = (options.isSsl() ? "https" : "http") + "://" + host + ":" + port; synchronized (vertx.sharedHttpServers()) { id = new ServerID(port, host); HttpServerImpl shared = vertx.sharedHttpServers().get(id); if (shared == null) { serverChannelGroup = new DefaultChannelGroup("conekt-acceptor-channels", GlobalEventExecutor.INSTANCE); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(vertx.getAcceptorEventLoopGroup(), availableWorkers); bootstrap.channelFactory(new VertxNioServerChannelFactory()); applyConnectionOptions(bootstrap); sslHelper.validate(vertx); bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { if (requestStream.isPaused() || wsStream.isPaused()) { ch.close(); return; } ChannelPipeline pipeline = ch.pipeline(); if (sslHelper.isSSL()) { pipeline.addLast("ssl", sslHelper.createSslHandler(vertx, false)); } pipeline.addLast("httpDecoder", new HttpRequestDecoder(options.getMaxInitialLineLength(), options.getMaxHeaderSize(), options.getMaxChunkSize(), false)); pipeline.addLast("httpEncoder", new VertxHttpResponseEncoder()); if (options.isCompressionSupported()) { pipeline.addLast("deflater", new HttpChunkContentCompressor()); } if (sslHelper.isSSL() || options.isCompressionSupported()) { // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used. pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support } if (options.getIdleTimeout() > 0) { pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout())); } pipeline.addLast("handler", new ServerHandler()); } }); addHandlers(this, listenContext); try { bindFuture = bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host), port)); Channel serverChannel = bindFuture.channel(); serverChannelGroup.add(serverChannel); bindFuture.addListener(channelFuture -> { if (!channelFuture.isSuccess()) { vertx.sharedHttpServers().remove(id); } else { metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options); } }); } catch (final Throwable t) { // Make sure we send the exception back through the handler (if any) if (listenHandler != null) { vertx.runOnContext(v -> listenHandler.handle(Future.failedFuture(t))); } else { // No handler - log so user can see failure log.error("", t); } listening = false; return this; } vertx.sharedHttpServers().put(id, this); actualServer = this; } else { // Server already exists with that host/port - we will use that actualServer = shared; addHandlers(actualServer, listenContext); metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options); } actualServer.bindFuture.addListener(future -> { if (listenHandler != null) { final AsyncResult<HttpServer> res; if (future.isSuccess()) { res = Future.succeededFuture(HttpServerImpl.this); } else { res = Future.failedFuture(future.cause()); listening = false; } listenContext.runOnContext((v) -> listenHandler.handle(res)); } else if (!future.isSuccess()) { listening = false; // No handler - log so user can see failure log.error("", future.cause()); } }); } return this; }
From source file:io.advantageous.conekt.net.impl.NetServerImpl.java
License:Open Source License
@Override public synchronized NetServer listen(int port, String host, Handler<AsyncResult<NetServer>> listenHandler) { if (connectStream.handler() == null) { throw new IllegalStateException("Set connect handler first"); }//from www . j a va 2s . c o m if (listening) { throw new IllegalStateException("Listen already called"); } listening = true; listenContext = vertx.getOrCreateContext(); synchronized (vertx.sharedNetServers()) { this.actualPort = port; // Will be updated on bind for a wildcard port id = new ServerID(port, host); NetServerImpl shared = vertx.sharedNetServers().get(id); if (shared == null || port == 0) { // Wildcard port will imply a new actual server each time serverChannelGroup = new DefaultChannelGroup("conekt-acceptor-channels", GlobalEventExecutor.INSTANCE); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(availableWorkers); bootstrap.channel(NioServerSocketChannel.class); sslHelper.validate(vertx); bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { if (connectStream.isPaused()) { ch.close(); return; } ChannelPipeline pipeline = ch.pipeline(); if (sslHelper.isSSL()) { SslHandler sslHandler = sslHelper.createSslHandler(vertx, false); pipeline.addLast("ssl", sslHandler); } if (sslHelper.isSSL()) { // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used. pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support } if (options.getIdleTimeout() > 0) { pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout())); } pipeline.addLast("handler", new ServerHandler()); } }); applyConnectionOptions(bootstrap); if (connectStream.handler() != null) { handlerManager.addHandler(connectStream.handler(), listenContext); } try { InetSocketAddress addr = new InetSocketAddress(InetAddress.getByName(host), port); bindFuture = bootstrap.bind(addr).addListener(future -> runListeners()); this.addListener(() -> { if (bindFuture.isSuccess()) { log.trace( "Net server listening on " + host + ":" + bindFuture.channel().localAddress()); // Update port to actual port - wildcard port 0 might have been used NetServerImpl.this.actualPort = ((InetSocketAddress) bindFuture.channel() .localAddress()).getPort(); NetServerImpl.this.id = new ServerID(NetServerImpl.this.actualPort, id.host); vertx.sharedNetServers().put(id, NetServerImpl.this); metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(id.port, id.host), options); } else { vertx.sharedNetServers().remove(id); } }); serverChannelGroup.add(bindFuture.channel()); } catch (Throwable t) { // Make sure we send the exception back through the handler (if any) if (listenHandler != null) { vertx.runOnContext(v -> listenHandler.handle(Future.failedFuture(t))); } else { // No handler - log so user can see failure log.error("", t); } listening = false; return this; } if (port != 0) { vertx.sharedNetServers().put(id, this); } actualServer = this; } else { // Server already exists with that host/port - we will use that actualServer = shared; this.actualPort = shared.actualPort(); metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(id.port, id.host), options); if (connectStream.handler() != null) { actualServer.handlerManager.addHandler(connectStream.handler(), listenContext); } } // just add it to the future so it gets notified once the bind is complete actualServer.addListener(() -> { if (listenHandler != null) { AsyncResult<NetServer> res; if (actualServer.bindFuture.isSuccess()) { res = Future.succeededFuture(NetServerImpl.this); } else { listening = false; res = Future.failedFuture(actualServer.bindFuture.cause()); } // Call with expectRightThread = false as if server is already listening // Netty will call future handler immediately with calling thread // which might be a non Vert.x thread (if running embedded) listenContext.runOnContext(v -> listenHandler.handle(res)); } else if (!actualServer.bindFuture.isSuccess()) { // No handler - log so user can see failure log.error("Failed to listen", actualServer.bindFuture.cause()); listening = false; } }); } return this; }
From source file:io.advantageous.conekt.test.core.EventLoopGroupTest.java
License:Open Source License
@Test public void testNettyServerUsesContextEventLoop() throws Exception { ContextInternal context = (ContextInternal) conekt.getOrCreateContext(); AtomicReference<Thread> contextThread = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); context.runOnContext(v -> {// ww w . jav a 2 s . co m contextThread.set(Thread.currentThread()); latch.countDown(); }); awaitLatch(latch); ServerBootstrap bs = new ServerBootstrap(); bs.group(context.nettyEventLoop()); bs.channel(NioServerSocketChannel.class); bs.option(ChannelOption.SO_BACKLOG, 100); bs.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); }); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; assertEquals("hello", buf.toString(StandardCharsets.UTF_8)); assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); }); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Conekt.currentContext()); testComplete(); }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { fail(cause.getMessage()); } }); }); } }); bs.bind("localhost", 1234).sync(); conekt.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> { assertTrue(ar.succeeded()); NetSocket so = ar.result(); so.write(Buffer.buffer("hello")); }); await(); }
From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java
License:Apache License
private CompletableFuture<Void> startAcceptingConnections() { CompletableFuture<Void> future = new CompletableFuture<>(); ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_REUSEADDR, true); b.option(ChannelOption.SO_BACKLOG, 128); b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024)); b.childOption(ChannelOption.SO_RCVBUF, 1024 * 1024); b.childOption(ChannelOption.SO_SNDBUF, 1024 * 1024); b.childOption(ChannelOption.SO_KEEPALIVE, true); b.childOption(ChannelOption.TCP_NODELAY, true); b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); b.group(serverGroup, clientGroup);/*w w w.j ava2 s . c o m*/ b.channel(serverChannelClass); if (enableNettyTls) { b.childHandler(new SslServerCommunicationChannelInitializer()); } else { b.childHandler(new BasicChannelInitializer()); } // Bind and start to accept incoming connections. b.bind(localAddress.port()).addListener((ChannelFutureListener) f -> { if (f.isSuccess()) { log.info("{} accepting incoming connections on port {}", localAddress.address(true), localAddress.port()); serverChannel = f.channel(); future.complete(null); } else { log.warn("{} failed to bind to port {} due to {}", localAddress.address(true), localAddress.port(), f.cause()); future.completeExceptionally(f.cause()); } }); return future; }