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:io.nodyn.tcp.TCPWrap.java
License:Apache License
public void listen(int backlog) { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(this.process.getEventLoop().getEventLoopGroup()); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override// ww w . j a va 2 s . c om protected void initChannel(Channel ch) throws Exception { ch.config().setAutoRead(false); // ch.pipeline().addLast("debug", new DebugHandler("server")); ch.pipeline().addLast("emit.connection", new ConnectionEventHandler(TCPWrap.this.process, TCPWrap.this)); ch.pipeline().addLast("handle", new UnrefHandler(TCPWrap.this)); } }); this.channelFuture = bootstrap.bind(this.addr, this.port); this.channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { // TODO callback error } }); ref(); }
From source file:io.reactivex.netty.server.RxServer.java
License:Apache License
public RxServer(ServerBootstrap bootstrap, int port, final PipelineConfigurator<I, O> pipelineConfigurator, final ConnectionHandler<I, O> connectionHandler, EventExecutorGroup connHandlingExecutor) { super(bootstrap, port); this.pipelineConfigurator = pipelineConfigurator; bootstrap .childHandler(newChannelInitializer(pipelineConfigurator, connectionHandler, connHandlingExecutor)); }
From source file:io.syncframework.netty.ServerImpl.java
License:Apache License
@Override public void init() { String basedir = System.getProperty(Globals.SYNC_BASE); ///*from www. ja va 2 s . c o m*/ // configure & initialize logging subsystem with logback // File logbackfile = new File(basedir, "logback.xml"); if (logbackfile.exists() && logbackfile.isFile()) { try { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); configurator.doConfigure(logbackfile); } catch (JoranException je) { System.err.println(this + " has failed to configure logback: " + je.getMessage()); je.printStackTrace(); System.exit(1); } } if (log.isInfoEnabled()) log.info("{} initializing using directory {}", this, basedir); File mimesfile = new File(basedir, "conf" + File.separator + "mime.types"); if (mimesfile.exists()) { if (log.isTraceEnabled()) log.trace("{} loading mimes from {}", this, mimesfile.getAbsolutePath()); try { MimeUtils.init(mimesfile); } catch (Exception e) { log.error("{} has failed to initialize mimes.type file: {}", this, mimesfile, e); System.exit(1); } } else { if (log.isTraceEnabled()) log.trace("{} loading default/known mime types.", this); MimeUtils.init(); } // init configuration File configFile = new File(basedir, Globals.SERVER_PROPERTIES); try { FileInputStream fis = new FileInputStream(configFile); config.load(fis); } catch (FileNotFoundException e) { log.error("{} has failed to locate {}", this, configFile); System.exit(1); } catch (IOException e) { log.error("{} has failed to read configuration file {}", this, configFile); System.exit(1); } File appdir = new File(basedir, Globals.APPLICATIONS_DIRNAME); if (!appdir.isDirectory()) { System.err.println("directory " + appdir.getAbsolutePath() + " does not exist"); System.exit(1); } // scan for .sar files File files[] = appdir.listFiles(new FileFilter() { public boolean accept(File f) { if (f.getName().endsWith(".sar")) return true; return false; } }); // unpacking sar files... for (File sar : files) { try { if (log.isInfoEnabled()) log.info("deploying SAR {}", sar.getName()); SarUtils.unpack(sar, appdir); } catch (Exception e) { log.error("failed to uncompress sar file {}: {}", sar.getName(), e); } } // scan for directories files = appdir.listFiles(new FileFilter() { public boolean accept(File f) { if (f.isDirectory()) return true; return false; } }); applications = new LinkedList<Application>(); for (File dir : files) { Application application = new Application(dir); try { application.start(); ApplicationManager.register(application); applications.add(application); } catch (Throwable t) { log.error("{} has failed to initialize application: {}", this, application); log.error("exception caught: ", t); log.error("invalidating {} until the problem is fixed", application); } } Runtime.getRuntime().addShutdownHook(new Thread("shutdown") { public void run() { if (log.isInfoEnabled()) log.info("{} is initializing graceful shutdown", this); // stopping process for (Application application : applications) { try { if (log.isInfoEnabled()) log.info("stopping {}", application); application.stop(); } catch (Exception e) { log.error("{} failed to stop {}: ", this, application, e); } } if (log.isInfoEnabled()) log.info("@Applications stopped. Goodbye!"); } }); EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.childHandler(new ServerInitializer(this)); try { ChannelFuture chf = null; if (config.getListenAddress() != null) chf = b.bind(config.getListenAddress(), config.getListenPort()); else chf = b.bind(config.getListenPort()); Channel ch = chf.sync().channel(); ch.closeFuture().sync(); } catch (Exception e) { log.error("{} has failed to bind to socket: ", this, e); System.exit(1); } } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:io.vertx.core.EventLoopGroupTest.java
License:Open Source License
@Test public void testNettyServerUsesContextEventLoop() throws Exception { ContextInternal context = (ContextInternal) vertx.getOrCreateContext(); AtomicReference<Thread> contextThread = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); context.runOnContext(v -> {/* w ww . j av a 2 s . c o m*/ contextThread.set(Thread.currentThread()); latch.countDown(); }); awaitLatch(latch); ServerBootstrap bs = new ServerBootstrap(); bs.group(context.nettyEventLoop()); bs.channelFactory(((VertxInternal) vertx).transport().serverChannelFactory(false)); 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(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.currentContext()); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.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(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.currentContext()); }); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.currentContext()); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.currentContext()); testComplete(); }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { fail(cause.getMessage()); } }); }); } }); ChannelFuture fut = bs.bind("localhost", 1234); try { fut.sync(); vertx.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> { assertTrue(ar.succeeded()); NetSocket so = ar.result(); so.write(Buffer.buffer("hello")); }); await(); } finally { fut.channel().close().sync(); } }
From source file:io.vertx.core.http.Http2ClientTest.java
License:Open Source License
private ServerBootstrap createH2Server( BiFunction<Http2ConnectionDecoder, Http2ConnectionEncoder, Http2FrameListener> handler) { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.channel(NioServerSocketChannel.class); NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(); eventLoopGroups.add(eventLoopGroup); bootstrap.group(eventLoopGroup);//from ww w. j a v a 2 s . c o m bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { SSLHelper sslHelper = new SSLHelper(serverOptions, Cert.SERVER_JKS.get(), null); SslHandler sslHandler = new SslHandler( sslHelper.setApplicationProtocols(Arrays.asList(HttpVersion.HTTP_2, HttpVersion.HTTP_1_1)) .createEngine((VertxInternal) vertx, DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT)); ch.pipeline().addLast(sslHandler); ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler("whatever") { @Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { ChannelPipeline p = ctx.pipeline(); Http2ConnectionHandler clientHandler = createHttpConnectionHandler(handler); p.addLast("handler", clientHandler); return; } ctx.close(); throw new IllegalStateException("unknown protocol: " + protocol); } }); } }); return bootstrap; }
From source file:io.vertx.core.http.Http2ClientTest.java
License:Open Source License
private ServerBootstrap createH2CServer( BiFunction<Http2ConnectionDecoder, Http2ConnectionEncoder, Http2FrameListener> handler, boolean upgrade) { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.channel(NioServerSocketChannel.class); bootstrap.group(new NioEventLoopGroup()); bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override//w ww .ja va 2s.com protected void initChannel(Channel ch) throws Exception { if (upgrade) { HttpServerCodec sourceCodec = new HttpServerCodec(); HttpServerUpgradeHandler.UpgradeCodecFactory upgradeCodecFactory = protocol -> { if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { Http2ConnectionHandler httpConnectionHandler = createHttpConnectionHandler((a, b) -> { return new Http2FrameListenerDecorator(handler.apply(a, b)) { @Override public void onSettingsRead(ChannelHandlerContext ctx, io.netty.handler.codec.http2.Http2Settings settings) throws Http2Exception { super.onSettingsRead(ctx, settings); Http2Connection conn = a.connection(); Http2Stream stream = conn.stream(1); DefaultHttp2Headers blah = new DefaultHttp2Headers(); blah.status("200"); b.frameWriter().writeHeaders(ctx, 1, blah, 0, true, ctx.voidPromise()); } }; }); return new Http2ServerUpgradeCodec(httpConnectionHandler); } else { return null; } }; ch.pipeline().addLast(sourceCodec); ch.pipeline().addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory)); } else { Http2ConnectionHandler clientHandler = createHttpConnectionHandler(handler); ch.pipeline().addLast("handler", clientHandler); } } }); return bootstrap; }
From source file:io.vertx.core.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 2 s .co m*/ if (listening) { throw new IllegalStateException("Already listening"); } listenContext = vertx.getOrCreateContext(); listening = true; serverOrigin = (options.isSsl() ? "https" : "http") + "://" + host + ":" + port; List<HttpVersion> applicationProtocols = options.getAlpnVersions(); if (listenContext.isWorkerContext()) { applicationProtocols = applicationProtocols.stream().filter(v -> v != HttpVersion.HTTP_2) .collect(Collectors.toList()); } sslHelper.setApplicationProtocols(applicationProtocols); synchronized (vertx.sharedHttpServers()) { this.actualPort = port; // Will be updated on bind for a wildcard port id = new ServerID(port, host); HttpServerImpl shared = vertx.sharedHttpServers().get(id); if (shared == null || port == 0) { serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels", GlobalEventExecutor.INSTANCE); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(vertx.getAcceptorEventLoopGroup(), availableWorkers); bootstrap.channel(NioServerSocketChannel.class); 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)); if (options.isUseAlpn()) { pipeline.addLast("alpn", new ApplicationProtocolNegotiationHandler("http/1.1") { @Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception { if (protocol.equals("http/1.1")) { configureHttp1(pipeline); } else { handleHttp2(ch); } } }); } else { configureHttp1(pipeline); } } else { if (DISABLE_HC2) { configureHttp1(pipeline); } else { pipeline.addLast(new Http1xOrHttp2Handler()); } } } }); addHandlers(this, listenContext); try { bindFuture = AsyncResolveConnectHelper.doBind(vertx, port, host, bootstrap); bindFuture.addListener(res -> { if (res.failed()) { vertx.sharedHttpServers().remove(id); } else { Channel serverChannel = res.result(); HttpServerImpl.this.actualPort = ((InetSocketAddress) serverChannel.localAddress()) .getPort(); serverChannelGroup.add(serverChannel); 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; this.actualPort = shared.actualPort; 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.succeeded()) { res = Future.succeededFuture(HttpServerImpl.this); } else { res = Future.failedFuture(future.cause()); listening = false; } listenContext.runOnContext((v) -> listenHandler.handle(res)); } else if (future.failed()) { listening = false; // No handler - log so user can see failure log.error(future.cause()); } }); } return this; }
From source file:io.vertx.core.net.impl.NetServerBase.java
License:Open Source License
public synchronized void listen(Handler<? super C> handler, int port, String host, Handler<AsyncResult<Void>> listenHandler) { if (handler == null) { throw new IllegalStateException("Set connect handler first"); }/*from ww w . ja v a 2s .c o m*/ if (listening) { throw new IllegalStateException("Listen already called"); } listening = true; listenContext = vertx.getOrCreateContext(); registeredHandler = handler; synchronized (vertx.sharedNetServers()) { this.actualPort = port; // Will be updated on bind for a wildcard port id = new ServerID(port, host); NetServerBase shared = vertx.sharedNetServers().get(id); if (shared == null || port == 0) { // Wildcard port will imply a new actual server each time serverChannelGroup = new DefaultChannelGroup("vertx-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 (isPaused()) { ch.close(); return; } ChannelPipeline pipeline = ch.pipeline(); NetServerBase.this.initChannel(ch.pipeline()); pipeline.addLast("handler", new ServerHandler(ch)); } }); applyConnectionOptions(bootstrap); handlerManager.addHandler(handler, listenContext); try { bindFuture = AsyncResolveConnectHelper.doBind(vertx, port, host, bootstrap); bindFuture.addListener(res -> { if (res.succeeded()) { Channel ch = res.result(); log.trace("Net server listening on " + host + ":" + ch.localAddress()); // Update port to actual port - wildcard port 0 might have been used NetServerBase.this.actualPort = ((InetSocketAddress) ch.localAddress()).getPort(); NetServerBase.this.id = new ServerID(NetServerBase.this.actualPort, id.host); serverChannelGroup.add(ch); vertx.sharedNetServers().put(id, NetServerBase.this); metrics = vertx.metricsSPI().createMetrics(new SocketAddressImpl(id.port, id.host), options); } else { vertx.sharedNetServers().remove(id); } }); } 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; } 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(new SocketAddressImpl(id.port, id.host), options); actualServer.handlerManager.addHandler(handler, listenContext); } // just add it to the future so it gets notified once the bind is complete actualServer.bindFuture.addListener(res -> { if (listenHandler != null) { AsyncResult<Void> ares; if (res.succeeded()) { ares = Future.succeededFuture(); } else { listening = false; ares = Future.failedFuture(res.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(ares)); } else if (res.failed()) { // No handler - log so user can see failure log.error("Failed to listen", res.cause()); listening = false; } }); } return; }
From source file:io.vertx.test.core.EventLoopGroupTest.java
License:Open Source License
@Test public void testNettyServerUsesContextEventLoop() throws Exception { ContextInternal context = (ContextInternal) vertx.getOrCreateContext(); AtomicReference<Thread> contextThread = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); context.runOnContext(v -> {// w w w. j ava 2s.c o 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, Vertx.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, Vertx.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, Vertx.currentContext()); }); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(() -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.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, Vertx.currentContext()); testComplete(); }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { fail(cause.getMessage()); } }); }); } }); bs.bind("localhost", 1234).sync(); vertx.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> { assertTrue(ar.succeeded()); NetSocket so = ar.result(); so.write(Buffer.buffer("hello")); }); await(); }
From source file:io.vertx.test.core.Http2ClientTest.java
License:Open Source License
private ServerBootstrap createH2Server( BiFunction<Http2ConnectionDecoder, Http2ConnectionEncoder, Http2FrameListener> handler) { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.channel(NioServerSocketChannel.class); NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(); eventLoopGroups.add(eventLoopGroup); bootstrap.group(eventLoopGroup);//from w w w. ja va 2 s.co m bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { SSLHelper sslHelper = new SSLHelper(serverOptions, Cert.SERVER_JKS.get(), null); SslHandler sslHandler = sslHelper .setApplicationProtocols(Arrays.asList(HttpVersion.HTTP_2, HttpVersion.HTTP_1_1)) .createSslHandler((VertxInternal) vertx, DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT); ch.pipeline().addLast(sslHandler); ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler("whatever") { @Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { ChannelPipeline p = ctx.pipeline(); Http2ConnectionHandler clientHandler = createHttpConnectionHandler(handler); p.addLast("handler", clientHandler); return; } ctx.close(); throw new IllegalStateException("unknown protocol: " + protocol); } }); } }); return bootstrap; }