List of usage examples for io.netty.channel ChannelInitializer ChannelInitializer
ChannelInitializer
From source file:com.github.sparkfy.network.server.TransportServer.java
License:Apache License
private void init(String hostToBind, int portToBind) { IOMode ioMode = IOMode.valueOf(conf.ioMode()); EventLoopGroup bossGroup = NettyUtils.createEventLoop(ioMode, conf.serverThreads(), "shuffle-server"); EventLoopGroup workerGroup = bossGroup; PooledByteBufAllocator allocator = NettyUtils.createPooledByteBufAllocator(conf.preferDirectBufs(), true /* allowCache */, conf.serverThreads()); bootstrap = new ServerBootstrap().group(bossGroup, workerGroup) .channel(NettyUtils.getServerChannelClass(ioMode)).option(ChannelOption.ALLOCATOR, allocator) .childOption(ChannelOption.ALLOCATOR, allocator); if (conf.backLog() > 0) { bootstrap.option(ChannelOption.SO_BACKLOG, conf.backLog()); }//from www . j a v a2 s . c o m if (conf.receiveBuf() > 0) { bootstrap.childOption(ChannelOption.SO_RCVBUF, conf.receiveBuf()); } if (conf.sendBuf() > 0) { bootstrap.childOption(ChannelOption.SO_SNDBUF, conf.sendBuf()); } bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { RpcHandler rpcHandler = appRpcHandler; for (TransportServerBootstrap bootstrap : bootstraps) { rpcHandler = bootstrap.doBootstrap(ch, rpcHandler); } context.initializePipeline(ch, rpcHandler); } }); InetSocketAddress address = hostToBind == null ? new InetSocketAddress(portToBind) : new InetSocketAddress(hostToBind, portToBind); channelFuture = bootstrap.bind(address); channelFuture.syncUninterruptibly(); port = ((InetSocketAddress) channelFuture.channel().localAddress()).getPort(); logger.debug("Shuffle server started on port :" + port); }
From source file:com.github.vitrifiedcode.javautilities.netty.DiscardServer.java
License:Open Source License
public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1) EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/* ww w. j av a2 s .co m*/ ServerBootstrap b = new ServerBootstrap(); // (2) b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3) .childHandler(new ChannelInitializer<SocketChannel>() { // (4) @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new DiscardServerHandler()); } }).option(ChannelOption.SO_BACKLOG, 128) // (5) .childOption(ChannelOption.SO_KEEPALIVE, true); // (6) // Bind and start to accept incoming connections. ChannelFuture f = b.bind(port).sync(); // (7) // 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 { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
From source file:com.github.zk1931.jzab.NettyTransport.java
License:Apache License
/** * Constructs a NettyTransport object.//from w w w . ja va2 s.c o m * * @param hostPort "hostname:port" string. The netty transport binds to the * port specified in the string. * @param receiver receiver callback. * @param sslParam Ssl parameters. * @param dir the directory used to store the received file. */ public NettyTransport(String hostPort, final Receiver receiver, ZabConfig.SslParameters sslParam, final File dir) throws InterruptedException, GeneralSecurityException, IOException { super(receiver); this.keyStore = sslParam.getKeyStore(); this.trustStore = sslParam.getTrustStore(); this.keyStorePassword = sslParam.getKeyStorePassword() != null ? sslParam.getKeyStorePassword().toCharArray() : null; this.trustStorePassword = sslParam.getTrustStorePassword() != null ? sslParam.getTrustStorePassword().toCharArray() : null; this.dir = dir; if (isSslEnabled()) { initSsl(); } this.hostPort = hostPort; String[] address = hostPort.split(":", 2); int port = Integer.parseInt(address[1]); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128) .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { if (isSslEnabled()) { SSLEngine engine = serverContext.createSSLEngine(); engine.setUseClientMode(false); engine.setNeedClientAuth(true); ch.pipeline().addLast(new SslHandler(engine)); } // Incoming handlers ch.pipeline().addLast(new MainHandler()); ch.pipeline().addLast(new ServerHandshakeHandler()); ch.pipeline().addLast(new NotifyHandler()); ch.pipeline().addLast(new ServerErrorHandler()); } }); // Travis build fails once in a while because it fails to bind to a port. // This is most likely a transient failure. Retry binding for 5 times with // 1 second sleep in between before giving up. int bindRetryCount = 5; for (int i = 0;; i++) { try { channel = b.bind(port).sync().channel(); LOG.info("Server started: {}", hostPort); return; } catch (Exception ex) { if (i >= bindRetryCount) { throw ex; } LOG.debug("Failed to bind to {}. Retrying after 1 second.", hostPort); Thread.sleep(1000); } } }
From source file:com.github.zk1931.jzab.transport.NettyTransport.java
License:Apache License
/** * Constructs a NettyTransport object.//from w w w . j a va 2 s .c o m * * @param hostPort "hostname:port" string. The netty transport binds to the * port specified in the string. * @param receiver receiver callback. * @param sslParam Ssl parameters. * @param dir the directory used to store the received file. */ public NettyTransport(String hostPort, final Receiver receiver, SslParameters sslParam, final File dir) throws InterruptedException, GeneralSecurityException, IOException { super(receiver); this.keyStore = sslParam.getKeyStore(); this.trustStore = sslParam.getTrustStore(); this.keyStorePassword = sslParam.getKeyStorePassword() != null ? sslParam.getKeyStorePassword().toCharArray() : null; this.trustStorePassword = sslParam.getTrustStorePassword() != null ? sslParam.getTrustStorePassword().toCharArray() : null; this.dir = dir; if (isSslEnabled()) { initSsl(); } this.hostPort = hostPort; String[] address = hostPort.split(":", 2); int port = Integer.parseInt(address[1]); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128) .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { if (isSslEnabled()) { SSLEngine engine = serverContext.createSSLEngine(); engine.setUseClientMode(false); engine.setNeedClientAuth(true); ch.pipeline().addLast(new SslHandler(engine)); } // Incoming handlers ch.pipeline().addLast(new MainHandler()); ch.pipeline().addLast(new ServerHandshakeHandler()); ch.pipeline().addLast(new NotifyHandler()); ch.pipeline().addLast(new ErrorHandler()); // Outgoing handlers. ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4)); } }); // Travis build fails once in a while because it fails to bind to a port. // This is most likely a transient failure. Retry binding for 5 times with // 1 second sleep in between before giving up. int bindRetryCount = 5; for (int i = 0;; i++) { try { channel = b.bind(port).sync().channel(); LOG.info("Server started: {}", hostPort); return; } catch (Exception ex) { if (i >= bindRetryCount) { throw ex; } LOG.debug("Failed to bind to {}. Retrying after 1 second.", hostPort); Thread.sleep(1000); } } }
From source file:com.goide.dlv.DlvRemoteVmConnection.java
License:Apache License
@NotNull @Override// w ww . jav a 2 s . c o m public Bootstrap createBootstrap(@NotNull InetSocketAddress address, @NotNull final AsyncPromise<Vm> vmResult) { return createBootstrap().handler(new ChannelInitializer() { @Override protected void initChannel(@NotNull Channel channel) throws Exception { vmResult.setResult(new DlvVm(getDebugEventListener(), channel)); } }); }
From source file:com.google.cloud.pubsub.proxy.moquette.NettyAcceptor.java
License:Open Source License
private void initFactory(String host, int port, final PipelineInitializer pipeliner) { ServerBootstrap bootsrap = new ServerBootstrap(); bootsrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from ww w . ja va 2 s .c om*/ public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); try { pipeliner.init(pipeline); } catch (Throwable th) { LOG.error("Severe error during pipeline creation", th); throw th; } } }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true); try { // Bind and start to accept incoming connections. ChannelFuture future = bootsrap.bind(host, port); LOG.info("Server binded host: {}, port: {}", host, port); future.sync(); } catch (InterruptedException ex) { LOG.error(null, ex); } }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStoreTest.java
License:Open Source License
private ServerSocketChannel startServer(ChannelHandler handler) throws Exception { EventLoopGroup eventLoop = new NioEventLoopGroup(1); ServerBootstrap sb = new ServerBootstrap().group(eventLoop).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<NioSocketChannel>() { @Override/*from w ww . j av a2 s . c o m*/ protected void initChannel(NioSocketChannel ch) { ch.pipeline().addLast(new HttpServerCodec()); ch.pipeline().addLast(new HttpObjectAggregator(1000)); ch.pipeline().addLast(handler); } }); return ((ServerSocketChannel) sb.bind("localhost", 0).sync().channel()); }
From source file:com.graylog.splunk.output.senders.TCPSender.java
License:Open Source License
protected void createBootstrap(final EventLoopGroup workerGroup) { final Bootstrap bootstrap = new Bootstrap(); final SplunkSenderThread senderThread = new SplunkSenderThread(queue); bootstrap.group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) .remoteAddress(new InetSocketAddress(hostname, port)) .handler(new ChannelInitializer<SocketChannel>() { @Override/*from www . j a v a 2 s .c om*/ protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new StringEncoder()); ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { // we only send data, never read on the socket } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { senderThread.start(ctx.channel()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { LOG.info("Channel disconnected."); senderThread.stop(); scheduleReconnect(ctx.channel().eventLoop()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOG.error("Exception caught", cause); } }); } }); bootstrap.connect().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { LOG.info("Connected."); } else { LOG.error("Connection failed: {}", future.cause().getMessage()); scheduleReconnect(future.channel().eventLoop()); } } }); }
From source file:com.grillecube.client.network.ClientNetwork.java
public void start(String host, int port) throws Exception { this.workerGroup = new NioEventLoopGroup(); this.bootstrap = new Bootstrap(); // (1) this.bootstrap.group(this.workerGroup); // (2) this.bootstrap.channel(NioSocketChannel.class); // (3) this.bootstrap.option(ChannelOption.SO_KEEPALIVE, true); // (4) this.bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override/* w w w . java2 s . c om*/ public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new TimeClientHandler()); } }); // Start the client. try { this.channel = this.bootstrap.connect(host, port).sync(); // (5) } catch (Exception exception) { // args are: quiettime, timeout, time unit this.workerGroup.shutdownGracefully(0, 10, TimeUnit.SECONDS); Logger.get().log(Level.ERROR, "Couldnt connect to host: " + host + ":" + port); exception.printStackTrace(Logger.get().getPrintStream()); this.bootstrap = null; this.channel = null; this.workerGroup = null; } }
From source file:com.grillecube.engine.network.client.ClientNetwork.java
public void start(String host, int port) throws Exception { this._workergroup = new NioEventLoopGroup(); this._bootstrap = new Bootstrap(); // (1) this._bootstrap.group(this._workergroup); // (2) this._bootstrap.channel(NioSocketChannel.class); // (3) this._bootstrap.option(ChannelOption.SO_KEEPALIVE, true); // (4) this._bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override// ww w . ja va 2 s.c o m public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new TimeClientHandler()); } }); // Start the client. try { this._channel = this._bootstrap.connect(host, port).sync(); // (5) } catch (Exception exception) { // args are: quiettime, timeout, time unit this._workergroup.shutdownGracefully(0, 10, TimeUnit.SECONDS); Logger.get().log(Level.ERROR, "Couldnt connect to host: " + host + ":" + port); exception.printStackTrace(Logger.get().getPrintStream()); this._bootstrap = null; this._channel = null; this._workergroup = null; } }