List of usage examples for io.netty.bootstrap ServerBootstrap group
@Override
public ServerBootstrap group(EventLoopGroup group)
From source file:NettyHttpListner.java
License:Apache License
public void start() { System.out.println("Starting the server..."); System.out.println("Starting Inbound Http Listner on Port " + this.port); // Configure SSL. SslContext sslCtx = null;/*from w ww . j a v a 2s .c o m*/ if (SSL) { try { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } catch (CertificateException ex) { Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex); } catch (SSLException ex) { Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex); } } commonEventLoopGroup = new NioEventLoopGroup(bossGroupSize); // bossGroup = new NioEventLoopGroup(bossGroupSize); // workerGroup = new NioEventLoopGroup(workerGroupSize); try { ServerBootstrap b = new ServerBootstrap(); // b.commonEventLoopGroup(bossGroup, workerGroup) b.group(commonEventLoopGroup).channel(NioServerSocketChannel.class) .childHandler( new NettyHttpTransportHandlerInitializer(HOST, HOST_PORT, maxConnectionsQueued, sslCtx)) .childOption(ChannelOption.AUTO_READ, false); b.option(ChannelOption.TCP_NODELAY, true); b.childOption(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_BACKLOG, maxConnectionsQueued); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000); b.option(ChannelOption.SO_SNDBUF, 1048576); b.option(ChannelOption.SO_RCVBUF, 1048576); b.childOption(ChannelOption.SO_RCVBUF, 1048576); b.childOption(ChannelOption.SO_SNDBUF, 1048576); b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); Channel ch = null; try { ch = b.bind(port).sync().channel(); ch.closeFuture().sync(); System.out.println("Inbound Listner Started"); } catch (InterruptedException e) { System.out.println("Exception caught"); } } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:alluxio.network.protocol.RPCMessageIntegrationTest.java
License:Apache License
@BeforeClass public static void beforeClass() { sEventClient = new NioEventLoopGroup(1); sEventServer = new NioEventLoopGroup(1); sIncomingHandler = new MessageSavingHandler(); // Setup the server. ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(sEventServer); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(new PipelineInitializer(sIncomingHandler)); InetSocketAddress address = new InetSocketAddress(NetworkAddressUtils.getLocalHostName(100), Constants.DEFAULT_MASTER_PORT); ChannelFuture cf = bootstrap.bind(address).syncUninterruptibly(); sLocalAddress = cf.channel().localAddress(); // Setup the client. sBootstrapClient = new Bootstrap(); sBootstrapClient.group(sEventClient); sBootstrapClient.channel(NioSocketChannel.class); sBootstrapClient.handler(new PipelineInitializer(new MessageSavingHandler())); }
From source file:at.yawk.dbus.protocol.DbusConnectorTest.java
@Test(enabled = false) public void testServer() throws Exception { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.channel(EpollServerDomainSocketChannel.class); bootstrap.group(new EpollEventLoopGroup()); bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override/*from w w w. jav a2 s . c o m*/ protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new CommandCodec()).addLast(new ChannelDuplexHandler() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof NegotiateUnixFd) { ch.writeAndFlush(new Error("error")); } if (msg instanceof Begin) { ch.pipeline().addLast(new LoggingInboundAdapter()) .addLast(new DbusMainProtocol(new MessageConsumer() { @Override public boolean requireAccept(MessageHeader header) { return true; } @Override public void accept(DbusMessage message) { DbusMessage response = new DbusMessage(); MessageHeader header = new MessageHeader(); header.setMessageType(MessageType.ERROR); header.addHeader(HeaderField.REPLY_SERIAL, BasicObject.createUint32(message.getHeader().getSerial())); //header.addHeader(HeaderField.SIGNATURE, SignatureObject.create( // Collections.singletonList(BasicType.VARIANT))); header.addHeader(HeaderField.ERROR_NAME, BasicObject.createString("Error")); response.setHeader(header); MessageBody body = new MessageBody(); //body.add(VariantObject.create(BasicObject.createString("testing!"))); response.setBody(body); ch.writeAndFlush(response); } })); ch.pipeline().remove((Class) getClass()); ch.pipeline().remove(CommandCodec.class); } } }); ch.writeAndFlush(new Ok(UUID.randomUUID())); } }); bootstrap.bind(new DomainSocketAddress(new File("test"))); try { DbusUtil.callCommand(("dbus-send --address=unix:path=" + new File(".").getAbsolutePath() + "/test --dest=org.freedesktop.UPower --print-reply " + "/org/freedesktop/UPower/devices/DisplayDevice org.freedesktop.DBus.Properties.Get string:org" + ".freedesktop.UPower.Device string:State").split(" ")); } catch (Exception e) { e.printStackTrace(); } TimeUnit.DAYS.sleep(1); }
From source file:co.paralleluniverse.comsat.webactors.netty.WebActorTest.java
License:Open Source License
@Before public void setUp() throws InterruptedException, IOException { System.out.println("Clearing sessions"); WebActorHandler.sessions.clear();/* w w w.ja v a 2 s . com*/ group = new NioEventLoopGroup(); final ServerBootstrap b = new ServerBootstrap(); b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new LoggingHandler(LogLevel.INFO)); pipeline.addLast(new HttpRequestDecoder()); pipeline.addLast(new LoggingHandler(LogLevel.INFO)); pipeline.addLast(HTTP_RESPONSE_ENCODER_KEY, new HttpResponseEncoder()); pipeline.addLast(new LoggingHandler(LogLevel.INFO)); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new LoggingHandler(LogLevel.INFO)); pipeline.addLast(webActorHandlerCreatorInEffect.call()); } }); ch = b.bind(INET_PORT).sync(); AbstractEmbeddedServer.waitUrlAvailable("http://localhost:" + INET_PORT); System.err.println("Server is up"); }
From source file:com.android.tools.idea.diagnostics.crash.LocalTestServer.java
License:Apache License
public void start() throws Exception { ServerBootstrap b = new ServerBootstrap(); myEventLoopGroup = new OioEventLoopGroup(); b.group(myEventLoopGroup).channel(OioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override//w w w . j av a 2 s . c o m protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpServerCodec()); // Note: Netty's decompressor uses jcraft jzlib, which is not exported as a library // p.addLast(new HttpContentDecompressor()); p.addLast(new HttpObjectAggregator(32 * 1024)); // big enough to collect a full thread dump p.addLast(new ChannelInboundHandlerAdapter() { @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof FullHttpRequest)) { return; } FullHttpResponse response = myResponseSupplier.apply((FullHttpRequest) msg); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.write(cause.toString()).addListener(ChannelFutureListener.CLOSE); } }); } }); myChannel = b.bind(myPort).sync().channel(); }
From source file:com.digitalpetri.modbus.slave.ModbusTcpSlave.java
License:Apache License
public CompletableFuture<ModbusTcpSlave> bind(String host, int port) { CompletableFuture<ModbusTcpSlave> bindFuture = new CompletableFuture<>(); ServerBootstrap bootstrap = new ServerBootstrap(); ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() { @Override/*from w w w . ja va2s. c o m*/ protected void initChannel(SocketChannel channel) throws Exception { channelCounter.inc(); logger.info("channel initialized: {}", channel); channel.pipeline().addLast(new LoggingHandler(LogLevel.TRACE)); channel.pipeline() .addLast(new ModbusTcpCodec(new ModbusResponseEncoder(), new ModbusRequestDecoder())); channel.pipeline().addLast(new ModbusTcpSlaveHandler(ModbusTcpSlave.this)); channel.closeFuture().addListener(future -> channelCounter.dec()); } }; config.getBootstrapConsumer().accept(bootstrap); bootstrap.group(config.getEventLoop()).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(initializer) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.bind(host, port).addListener((ChannelFuture future) -> { if (future.isSuccess()) { Channel channel = future.channel(); serverChannels.put(channel.localAddress(), channel); bindFuture.complete(ModbusTcpSlave.this); } else { bindFuture.completeExceptionally(future.cause()); } }); return bindFuture; }
From source file:com.fjn.helper.frameworkex.netty.v4.echotest.EchoServer.java
License:Apache License
public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/*from w w w . j a v a 2 s . c o m*/ // Bootstraps the server ServerBootstrap b = new ServerBootstrap(); // Specifies NIO transport, local socket address b.group(group); b.childGroup(); b.channel(NioServerSocketChannel.class); b.localAddress(new InetSocketAddress(port)); // Adds handler to channel pipeline b.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoServerHandler()); } }); // Binds server, waits for server to close, and releases resources ChannelFuture f = b.bind().sync(); System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress()); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } }
From source file:com.flysoloing.learning.network.netty.http2.helloworld.multiplex.server.Http2Server.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*www . j av a 2 s . 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" : "http") + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { group.shutdownGracefully(); } }
From source file:com.flysoloing.learning.network.netty.http2.tiles.Http2Server.java
License:Apache License
public ChannelFuture start() throws Exception { final SslContext sslCtx = configureTLS(); ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() { @Override// ww w . j a v a2 s. c om protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new Http2OrHttpHandler()); } }); Channel ch = b.bind(PORT).sync().channel(); return ch.closeFuture(); }
From source file:com.flysoloing.learning.network.netty.http2.tiles.HttpServer.java
License:Apache License
public ChannelFuture start() throws Exception { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/*w w w .j a v a2 s . c o m*/ protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpRequestDecoder(), new HttpResponseEncoder(), new HttpObjectAggregator(MAX_CONTENT_LENGTH), new Http1RequestHandler()); } }); Channel ch = b.bind(PORT).sync().channel(); return ch.closeFuture(); }