List of usage examples for io.netty.bootstrap ServerBootstrap group
@Override
public ServerBootstrap group(EventLoopGroup group)
From source file:com.turn.ttorrent.client.io.PeerServer.java
License:Apache License
/** * Create and start a new listening service for our torrents, reporting * with our peer ID on the given address. * * <p>/*from w w w. java2s. c o m*/ * This binds to the first available port in the client port range * PORT_RANGE_START to PORT_RANGE_END. * </p> */ public void start() throws Exception { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(environment.getEventService()); bootstrap.channel(environment.getEventLoopType().getServerChannelType()); bootstrap.option(ChannelOption.SO_BACKLOG, 128); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new PeerServerHandshakeHandler(torrents)); } }); bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); // bootstrap.childOption(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES)); // TODO: Derive from PieceHandler.DEFAULT_BLOCK_SIZE // bootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024); // bootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); SocketAddress address = environment.getLocalPeerListenAddress(); if (address != null) { future = bootstrap.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 = bootstrap.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:com.vmware.xenon.common.http.netty.NettyHttpListener.java
License:Open Source License
@Override public void start(int port, String bindAddress) throws Throwable { this.nettyExecutorService = Executors.newFixedThreadPool(EVENT_LOOP_THREAD_COUNT, r -> new Thread(r, this.host.getUri().toString() + "/netty-listener/" + this.host.getId())); this.eventLoopGroup = new NioEventLoopGroup(EVENT_LOOP_THREAD_COUNT, this.nettyExecutorService); if (this.childChannelHandler == null) { this.childChannelHandler = new NettyHttpServerInitializer(this.host, this.sslContext, this.responsePayloadSizeLimit); }/*from w ww . j a v a 2s. co m*/ ServerBootstrap b = new ServerBootstrap(); b.group(this.eventLoopGroup).channel(NioServerSocketChannel.class).childHandler(this.childChannelHandler); InetSocketAddress addr; if (bindAddress != null) { addr = new InetSocketAddress(bindAddress, port); } else { this.host.log(Level.WARNING, "*** Binding to all interfaces, please supply a bindAddress instead ***"); addr = new InetSocketAddress(port); } this.serverChannel = b.bind(addr).sync().channel(); this.serverChannel.config().setOption(ChannelOption.SO_LINGER, 0); this.port = ((InetSocketAddress) this.serverChannel.localAddress()).getPort(); this.isListening = true; }
From source file:de.cubeisland.engine.core.webapi.ApiServer.java
License:Open Source License
/** * Starts the server/*from w w w .java2 s . c om*/ * * @return fluent interface */ public ApiServer start() throws ApiStartupException { if (!this.isRunning()) { final ServerBootstrap serverBootstrap = new ServerBootstrap(); try { this.eventLoopGroup.set(new NioEventLoopGroup(this.maxThreads.get(), this.core.getTaskManager().getThreadFactory())); serverBootstrap.group(this.eventLoopGroup.get()).channel(NioServerSocketChannel.class) .childHandler(new ApiServerInitializer(this.core, this)) .localAddress(this.bindAddress.get(), this.port.get()); this.bootstrap.set(serverBootstrap); this.channel.set(serverBootstrap.bind().sync().channel()); } catch (Exception e) { this.bootstrap.set(null); this.channel.set(null); this.eventLoopGroup.getAndSet(null).shutdownGracefully(2, 5, TimeUnit.SECONDS); throw new ApiStartupException("The API server failed to start!", e); } } return this; }
From source file:de.ruedigermoeller.reallive.client.wsgate.WebSocketGate.java
License:Open Source License
public void run() { // param(1) just example to show the thread model with 2 connected clients while live coding // EventLoopGroup bossGroup = new NioEventLoopGroup(1); // param(1) just example to show the thread model with 2 connected clients while live coding EventLoopGroup workerGroup = new NioEventLoopGroup(8); try {/*from w w w. java 2s . co m*/ // additional thread pool for blocking handler // final EventExecutorGroup executorGroup = new DefaultEventExecutorGroup(8); final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpRequestDecoder(), new HttpObjectAggregator(65536), new HttpResponseEncoder(), new WebSocketServerProtocolHandler("/websocket"), new WebSocketGateChannelHandler(WebSocketGate.this)); // normal example without another thread pool // register blocking or long lasting handler to additional thread pool // ch.pipeline().addLast(executorGroup, new JSUGWebSocketHandler(channels)); } }); final Channel channel; channel = bootstrap.bind(port).sync().channel(); System.out.println("server started on port: " + port); channel.closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { workerGroup.shutdown(); } }
From source file:divconq.web.WebModule.java
License:Open Source License
public void goOnline() { this.listenlock.lock(); try {/*from ww w . ja va 2 s . c o m*/ // don't try if already in online mode if (this.activelisteners.size() > 0) return; // typically we should have an extension, unless we are supporting RPC only // TODO if (WebSiteManager.instance.getDefaultExtension() == null) // log.warn(0, "No default extension for web server"); for (final XElement httpconfig : this.config.selectAll("HttpListener")) { final boolean secure = "True".equals(httpconfig.getAttribute("Secure")); int httpport = (int) StringUtil.parseInt(httpconfig.getAttribute("Port"), secure ? 443 : 80); // ------------------------------------------------- // message port // ------------------------------------------------- ServerBootstrap b = new ServerBootstrap(); // TODO consider using shared EventLoopGroup // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#25.0 b.group(Hub.instance.getEventLoopGroup()).channel(NioServerSocketChannel.class) .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator()) //.option(ChannelOption.SO_BACKLOG, 125) // this is probably not needed but serves as note to research .option(ChannelOption.TCP_NODELAY, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (secure) { SniHandler ssl = new SniHandler(WebModule.this.siteman); //SslHandler ssl = new SslHandler(WebModule.this.siteman.findSslContextFactory("root").getServerEngine()); pipeline.addLast("ssl", ssl); } //pipeline.addLast("codec-http", new HttpServerCodec()); //pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); pipeline.addLast("decoder", new HttpRequestDecoder(4096, 8192, 262144)); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // TODO maybe - but currently we selectively compress files which is more efficient // this can also be a cached & compressed response that way //pipeline.addLast("deflater", new HttpContentCompressor()); pipeline.addLast("handler", new ServerHandler(httpconfig, WebModule.this.siteman)); } }); try { // must wait here, both to keep the activelisteners listeners up to date // but also to make sure we don't release connectLock too soon ChannelFuture bfuture = b.bind(httpport).sync(); if (bfuture.isSuccess()) { Logger.info("Web Server listening - now listening for HTTP on TCP port " + httpport); this.activelisteners.put(httpport, bfuture.channel()); } else Logger.error("Web Server unable to bind: " + bfuture.cause()); } catch (InterruptedException x) { Logger.error("Web Server interrupted while binding: " + x); } catch (Exception x) { Logger.error("Web Server errored while binding: " + x); } } } finally { this.listenlock.unlock(); } this.siteman.online(); //for (IWebExtension ext : WebSiteManager.instance.extensions.values()) // ext.online(); }
From source file:example.http2.helloworld.frame.server.Http2Server.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {//w ww . j a v a 2s .c o m SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider) /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification. * Please refer to the HTTP/2 specification for cipher requirements. */ .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); } else { sslCtx = null; } // Configure the server. EventLoopGroup group = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new Http2ServerInitializer(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); System.err.println("Open your HTTP/2-enabled web browser and navigate to " + (SSL ? "https" : "example/http") + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { group.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); 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 {/* w ww.j a v a 2s.c o m*/ 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:http2.server.Http2Server.java
License:Apache License
public static void main(String[] args) throws Exception { System.setProperty("jsse.enableSNIExtension", "true"); // Configure SSL. try {/*from www . j a v a2 s. c o m*/ String password = "http2"; if (Security.getProvider("BC") == null) { Security.addProvider(new BouncyCastleProvider()); } KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(null); ks.setKeyEntry("alias", ((KeyPair) getPem(Config.getString("privateKey"))).getPrivate(), password.toCharArray(), new java.security.cert.Certificate[] { (X509Certificate) getPem(Config.getString("certificate")) }); kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, password.toCharArray()); } catch (Exception e) { logger.error("transfer from pem file to pkcs12 failed!", e); } final SslContext sslCtx; if (SSL) { SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; sslCtx = SslContextBuilder.forServer(kmf).sslProvider(provider) /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification. * Please refer to the HTTP/2 specification for cipher requirements. */ .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); } else { sslCtx = null; } // Configure the server. EventLoopGroup group = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new Http2ServerInitializer(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); System.err.println("Open your HTTP/2-enabled web browser and navigate to " + (SSL ? "https" : "http") + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { group.shutdownGracefully(); } }
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 w ww . ja v a2 s.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 -> {// w w w . j ava 2 s . c om 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(); }