List of usage examples for io.netty.channel ChannelInitializer ChannelInitializer
ChannelInitializer
From source file:com.hzq.nio.websocket.WebSocketServer.java
License:Apache License
public void run(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from w w w .j a va2s . c o m*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("http-codec", new HttpServerCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); pipeline.addLast("handler", new WebSocketServerHandler()); } }); Channel ch = b.bind(port).sync().channel(); System.out.println("Web socket server started at port " + port + '.'); System.out.println("Open your browser and navigate to http://localhost:" + port + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.ibasco.agql.core.transport.tcp.NettyBasicTcpTransport.java
License:Open Source License
public NettyBasicTcpTransport(ChannelType channelType) { super(channelType); NettyTransport transport = this; getBootstrap().handler(new ChannelInitializer<SocketChannel>() { @Override/* w w w . j a v a 2 s .com*/ protected void initChannel(SocketChannel ch) throws Exception { getChannelInitializer().initializeChannel(ch, transport); } }); }
From source file:com.ibasco.agql.core.transport.udp.NettyBasicUdpTransport.java
License:Open Source License
public NettyBasicUdpTransport(ChannelType channelType) { super(channelType); NettyTransport transport = this; getBootstrap().handler(new ChannelInitializer<NioDatagramChannel>() { @Override/*from w ww.j ava 2s.co m*/ protected void initChannel(NioDatagramChannel ch) throws Exception { getChannelInitializer().initializeChannel(ch, transport); } }); }
From source file:com.ibasco.agql.protocols.valve.source.query.logger.SourceLogListenService.java
License:Open Source License
/** * <p>Creates a new service using the specified {@link InetSocketAddress} to listen on and utilizing * the callback specified to notify listeners of source log events</p> * * @param listenAddress/*from w ww .j a v a 2s.c o m*/ * An {@link InetSocketAddress} where the listen service will bind or listen on * @param logEventCallback * A {@link Consumer} callback that will be called once a log event has been received */ public SourceLogListenService(InetSocketAddress listenAddress, Consumer<SourceLogEntry> logEventCallback) { this.listenAddress = listenAddress; bootstrap = new Bootstrap().localAddress(this.listenAddress).channel(NioDatagramChannel.class) .group(listenWorkGroup).handler(new ChannelInitializer<NioDatagramChannel>() { @Override protected void initChannel(NioDatagramChannel ch) throws Exception { ch.pipeline().addLast(new SourceLogListenHandler(logEventCallback)); } }); SourceLogListenService service = this; //Add shutdown hook Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { log.debug("Service Interrupted. Shutting down gracefully."); service.shutdown(); } catch (InterruptedException e) { log.error(e.getMessage(), e); } } }); }
From source file:com.ibm.crail.datanode.netty.client.NettyEndpointGroup.java
License:Apache License
public NettyEndpointGroup() { workerGroup = new NioEventLoopGroup(); boot = new Bootstrap(); boot.group(workerGroup);/*from w w w . j av a 2 s. c o m*/ boot.channel(NioSocketChannel.class); boot.option(ChannelOption.SO_KEEPALIVE, true); final NettyEndpointGroup thisGroup = this; boot.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { /* outgoing pipeline */ //ch.pipeline().addLast(new RdmaEncoderTx()); /* incoming pipeline */ ch.pipeline().addLast(new RdmaDecoderRx(), new IncomingResponseHandler(thisGroup)); } }); activeClients = new ArrayList<NettyEndpoint>(); slot = new AtomicLong(0); inFlightOps = new ConcurrentHashMap<Long, NettyIOResult>(); }
From source file:com.ibm.crail.datanode.netty.server.NettyServer.java
License:Apache License
public void run() { /* start the netty server */ EventLoopGroup acceptGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/* www.j a va 2s . com*/ ServerBootstrap boot = new ServerBootstrap(); boot.group(acceptGroup, workerGroup); /* we use sockets */ boot.channel(NioServerSocketChannel.class); /* for new incoming connection */ boot.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { LOG.info("TID: " + Thread.currentThread().getId() + " , a new client connection has arrived from : " + ch.remoteAddress().toString()); /* incoming pipeline */ ch.pipeline().addLast(new RdmaDecoderRx(), /* this makes full RDMA messages */ new IncomingRequestHandler(ch, dataNode)); /* outgoing pipeline */ //ch.pipeline().addLast(new RdmaEncoderTx()); } }); /* general optimization settings */ boot.option(ChannelOption.SO_BACKLOG, 1024); boot.childOption(ChannelOption.SO_KEEPALIVE, true); /* now we bind the server and start */ ChannelFuture f = boot.bind(this.inetSocketAddress.getAddress(), this.inetSocketAddress.getPort()) .sync(); LOG.info("Datanode binded to : " + this.inetSocketAddress); /* at this point we are binded and ready */ f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { workerGroup.shutdownGracefully(); acceptGroup.shutdownGracefully(); LOG.info("Datanode at " + this.inetSocketAddress + " is shutdown"); } }
From source file:com.ibm.crail.namenode.rpc.netty.client.NettyRPCNamenodeClientGroup.java
License:Apache License
public NettyRPCNamenodeClientGroup() { workerGroup = new NioEventLoopGroup(); boot = new Bootstrap(); boot.group(workerGroup);//from www . j a va 2 s . c om boot.channel(NioSocketChannel.class); boot.option(ChannelOption.SO_KEEPALIVE, true); final NettyRPCNamenodeClientGroup thisGroup = this; boot.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { /* outgoing pipeline */ ch.pipeline().addLast(new RequestEncoder()); /* incoming pipeline */ ch.pipeline().addLast(new ResponseDecoder(thisGroup)); } }); slot = new AtomicLong(1); inFlightOps = new ConcurrentHashMap<Long, NettyResponse>(); activeClients = new ArrayList<NettyRPCNamenodeClient>(); }
From source file:com.ibm.crail.namenode.rpc.netty.NettyNameNode.java
License:Apache License
public void run(final RpcNameNodeService service) { /* here we run the incoming RPC service */ InetSocketAddress inetSocketAddress = CrailUtils.getNameNodeAddress(); LOG.info("Starting the NettyNamenode service at : " + inetSocketAddress); /* start the netty server */ EventLoopGroup acceptGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {//from ww w. j a v a 2 s . co m ServerBootstrap boot = new ServerBootstrap(); boot.group(acceptGroup, workerGroup); /* we use sockets */ boot.channel(NioServerSocketChannel.class); /* for new incoming connection */ boot.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { LOG.info("A new connection has arrived from : " + ch.remoteAddress().toString()); /* incoming pipeline */ ch.pipeline().addLast("RequestDecoder", new RequestDecoder()); ch.pipeline().addLast("NNProcessor", new NamenodeProcessor(service)); /* outgoing pipeline */ ch.pipeline().addLast("ResponseEncoder", new ResponseEncoder()); } }); /* general optimization settings */ boot.option(ChannelOption.SO_BACKLOG, 1024); boot.childOption(ChannelOption.SO_KEEPALIVE, true); /* now we bind the server and start */ ChannelFuture f = boot.bind(inetSocketAddress.getAddress(), inetSocketAddress.getPort()).sync(); /* at this point we are binded and ready */ f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { workerGroup.shutdownGracefully(); acceptGroup.shutdownGracefully(); LOG.info("Netty namenode at " + inetSocketAddress + " is shutdown"); } }
From source file:com.ibm.mqlight.api.impl.network.NettyNetworkService.java
License:Apache License
@Override public void connect(Endpoint endpoint, NetworkListener listener, Promise<NetworkChannel> promise) { final String methodName = "connect"; logger.entry(this, methodName, endpoint, listener, promise); SslContext sslCtx = null;/*w w w . ja va 2 s . co m*/ try { if (endpoint.getCertChainFile() != null && endpoint.getCertChainFile().exists()) { try (FileInputStream fileInputStream = new FileInputStream(endpoint.getCertChainFile())) { KeyStore jks = KeyStore.getInstance("JKS"); jks.load(fileInputStream, null); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(jks); sslCtx = SslContext.newClientContext(); if (sslCtx instanceof JdkSslContext) { ((JdkSslContext) sslCtx).context().init(null, trustManagerFactory.getTrustManagers(), null); } } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException | KeyManagementException e) { logger.data(this, methodName, e.toString()); } } // fallback to passing as .PEM file (or null, which loads default cacerts) if (sslCtx == null) { sslCtx = SslContext.newClientContext(endpoint.getCertChainFile()); } final SSLEngine sslEngine = sslCtx.newEngine(null, endpoint.getHost(), endpoint.getPort()); sslEngine.setUseClientMode(true); final LinkedList<String> enabledProtocols = new LinkedList<String>() { private static final long serialVersionUID = 7838479468739671083L; { for (String protocol : sslEngine.getSupportedProtocols()) { if (!disabledProtocolPattern.matcher(protocol).matches()) { add(protocol); } } } }; sslEngine.setEnabledProtocols(enabledProtocols.toArray(new String[0])); logger.data(this, methodName, "enabledProtocols", Arrays.toString(sslEngine.getEnabledProtocols())); final LinkedList<String> enabledCipherSuites = new LinkedList<String>() { private static final long serialVersionUID = 7838479468739671083L; { for (String cipher : sslEngine.getSupportedCipherSuites()) { if (!disabledCipherPattern.matcher(cipher).matches()) { add(cipher); } } } }; sslEngine.setEnabledCipherSuites(enabledCipherSuites.toArray(new String[0])); logger.data(this, methodName, "enabledCipherSuites", Arrays.toString(sslEngine.getEnabledCipherSuites())); if (endpoint.getVerifyName()) { SSLParameters sslParams = sslEngine.getSSLParameters(); sslParams.setEndpointIdentificationAlgorithm("HTTPS"); sslEngine.setSSLParameters(sslParams); } // The listener must be added to the ChannelFuture before the bootstrap channel initialisation completes (i.e. // before the NettyInboundHandler is added to the channel pipeline) otherwise the listener may not be able to // see the NettyInboundHandler, when its operationComplete() method is called (there is a small window where // the socket connection fails just after initChannel has complete but before ConnectListener is added, with // the ConnectListener.operationComplete() being called as though the connection was successful) // Hence we synchronise here and within the ChannelInitializer.initChannel() method. synchronized (bootstrapSync) { final ChannelHandler handler; if (endpoint.useSsl()) { handler = new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { synchronized (bootstrapSync) { ch.pipeline().addFirst(new SslHandler(sslEngine)); ch.pipeline().addLast(new NettyInboundHandler(ch)); } } }; } else { handler = new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { synchronized (bootstrapSync) { ch.pipeline().addLast(new NettyInboundHandler(ch)); } } }; } final Bootstrap bootstrap = getBootstrap(endpoint.useSsl(), sslEngine, handler); final ChannelFuture f = bootstrap.connect(endpoint.getHost(), endpoint.getPort()); f.addListener(new ConnectListener(endpoint, f, promise, listener)); } } catch (SSLException e) { if (e.getCause() == null) { promise.setFailure(new SecurityException(e.getMessage(), e)); } else { promise.setFailure(new SecurityException(e.getCause().getMessage(), e.getCause())); } } logger.exit(this, methodName); }
From source file:com.ict.dtube.remoting.netty.NettyRemotingClient.java
License:Apache License
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(// nettyClientConfig.getClientWorkerThreads(), // new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override/*from ww w . j a va 2 s . c o m*/ public Thread newThread(Runnable r) { return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet()); } }); Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class)// // .option(ChannelOption.TCP_NODELAY, true) // .option(ChannelOption.SO_SNDBUF, NettySystemConfig.SocketSndbufSize) // .option(ChannelOption.SO_RCVBUF, NettySystemConfig.SocketRcvbufSize) // .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(// defaultEventExecutorGroup, // new NettyEncoder(), // new NettyDecoder(), // new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()), // new NettyConnetManageHandler(), // new NettyClientHandler()); } }); // ?1?? this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingClient.this.scanResponseTable(); } catch (Exception e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); if (this.channelEventListener != null) { this.nettyEventExecuter.start(); } }