List of usage examples for io.netty.channel ChannelOption SO_REUSEADDR
ChannelOption SO_REUSEADDR
To view the source code for io.netty.channel ChannelOption SO_REUSEADDR.
Click Source Link
From source file:org.elasticsearch.hadoop.transport.netty4.Netty4Transport.java
License:Apache License
private void createServerBootstrap(String name, Settings settings) { if (logger.isDebugEnabled()) { logger.debug(/*from w w w .jav a 2s.co m*/ "using profile[{}], worker_count[{}], port[{}], bind_host[{}], publish_host[{}], compress[{}], " + "connect_timeout[{}], connections_per_node[{}/{}/{}/{}/{}], receive_predictor[{}->{}]", name, workerCount, settings.get("port"), settings.get("bind_host"), settings.get("publish_host"), compress, connectTimeout, connectionsPerNodeRecovery, connectionsPerNodeBulk, connectionsPerNodeReg, connectionsPerNodeState, connectionsPerNodePing, receivePredictorMin, receivePredictorMax); } final ThreadFactory workerFactory = daemonThreadFactory(this.settings, HTTP_SERVER_WORKER_THREAD_NAME_PREFIX, name); final ServerBootstrap serverBootstrap = new ServerBootstrap(); if (TCP_BLOCKING_SERVER.get(settings)) { serverBootstrap.group(new OioEventLoopGroup(workerCount, workerFactory)); serverBootstrap.channel(OioServerSocketChannel.class); } else { serverBootstrap.group(new NioEventLoopGroup(workerCount, workerFactory)); serverBootstrap.channel(NioServerSocketChannel.class); } serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("open_channels", Netty4Transport.this.serverOpenChannels); ch.pipeline().addLast("size", new Netty4SizeHeaderFrameDecoder()); ch.pipeline().addLast("dispatcher", new Netty4MessageChannelHandler(Netty4Transport.this, name)); } }); serverBootstrap.childOption(ChannelOption.TCP_NODELAY, TCP_NO_DELAY.get(settings)); serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, TCP_KEEP_ALIVE.get(settings)); final ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.getDefault(settings); if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) { serverBootstrap.childOption(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes())); } final ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.getDefault(settings); if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) { serverBootstrap.childOption(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.bytesAsInt())); } serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator); serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator); final boolean reuseAddress = TCP_REUSE_ADDRESS.get(settings); serverBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress); serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, reuseAddress); serverBootstrap.validate(); serverBootstraps.put(name, serverBootstrap); }
From source file:org.elasticsearch.http.netty4.Netty4HttpServerTransport.java
License:Apache License
@Override protected void doStart() { this.serverOpenChannels = new Netty4OpenChannelsHandler(logger); serverBootstrap = new ServerBootstrap(); if (blockingServer) { serverBootstrap.group(new OioEventLoopGroup(workerCount, daemonThreadFactory(settings, HTTP_SERVER_WORKER_THREAD_NAME_PREFIX))); serverBootstrap.channel(OioServerSocketChannel.class); } else {//from ww w . ja v a 2s .c om serverBootstrap.group(new NioEventLoopGroup(workerCount, daemonThreadFactory(settings, HTTP_SERVER_WORKER_THREAD_NAME_PREFIX))); serverBootstrap.channel(NioServerSocketChannel.class); } serverBootstrap.childHandler(configureServerChannelHandler()); serverBootstrap.childOption(ChannelOption.TCP_NODELAY, SETTING_HTTP_TCP_NO_DELAY.get(settings)); serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, SETTING_HTTP_TCP_KEEP_ALIVE.get(settings)); final ByteSizeValue tcpSendBufferSize = SETTING_HTTP_TCP_SEND_BUFFER_SIZE.get(settings); if (tcpSendBufferSize.bytes() > 0) { serverBootstrap.childOption(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes())); } final ByteSizeValue tcpReceiveBufferSize = SETTING_HTTP_TCP_RECEIVE_BUFFER_SIZE.get(settings); if (tcpReceiveBufferSize.bytes() > 0) { serverBootstrap.childOption(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.bytes())); } serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator); serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator); final boolean reuseAddress = SETTING_HTTP_TCP_REUSE_ADDRESS.get(settings); serverBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress); serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, reuseAddress); this.boundAddress = createBoundHttpAddress(); }
From source file:org.elasticsearch.transport.netty4.Netty4Transport.java
License:Apache License
private Bootstrap createBootstrap() { final Bootstrap bootstrap = new Bootstrap(); if (TCP_BLOCKING_CLIENT.get(settings)) { bootstrap.group(new OioEventLoopGroup(1, daemonThreadFactory(settings, TRANSPORT_CLIENT_WORKER_THREAD_NAME_PREFIX))); bootstrap.channel(OioSocketChannel.class); } else {/*w w w . j a va 2 s. c o m*/ bootstrap.group(new NioEventLoopGroup(workerCount, daemonThreadFactory(settings, TRANSPORT_CLIENT_BOSS_THREAD_NAME_PREFIX))); bootstrap.channel(NioSocketChannel.class); } bootstrap.handler(getClientChannelInitializer()); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(connectTimeout.millis())); bootstrap.option(ChannelOption.TCP_NODELAY, TCP_NO_DELAY.get(settings)); bootstrap.option(ChannelOption.SO_KEEPALIVE, TCP_KEEP_ALIVE.get(settings)); final ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.get(settings); if (tcpSendBufferSize.bytes() > 0) { bootstrap.option(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes())); } final ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.get(settings); if (tcpReceiveBufferSize.bytes() > 0) { bootstrap.option(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.bytes())); } bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator); final boolean reuseAddress = TCP_REUSE_ADDRESS.get(settings); bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress); bootstrap.validate(); return bootstrap; }
From source file:org.elasticsearch.transport.netty4.Netty4Transport.java
License:Apache License
private void createServerBootstrap(String name, Settings settings) { if (logger.isDebugEnabled()) { logger.debug(//www .ja v a2 s . co m "using profile[{}], worker_count[{}], port[{}], bind_host[{}], publish_host[{}], compress[{}], " + "connect_timeout[{}], connections_per_node[{}/{}/{}/{}/{}], receive_predictor[{}->{}]", name, workerCount, settings.get("port"), settings.get("bind_host"), settings.get("publish_host"), compress, connectTimeout, connectionsPerNodeRecovery, connectionsPerNodeBulk, connectionsPerNodeReg, connectionsPerNodeState, connectionsPerNodePing, receivePredictorMin, receivePredictorMax); } final ThreadFactory workerFactory = daemonThreadFactory(this.settings, TRANSPORT_SERVER_WORKER_THREAD_NAME_PREFIX, name); final ServerBootstrap serverBootstrap = new ServerBootstrap(); if (TCP_BLOCKING_SERVER.get(settings)) { serverBootstrap.group(new OioEventLoopGroup(workerCount, workerFactory)); serverBootstrap.channel(OioServerSocketChannel.class); } else { serverBootstrap.group(new NioEventLoopGroup(workerCount, workerFactory)); serverBootstrap.channel(NioServerSocketChannel.class); } serverBootstrap.childHandler(getServerChannelInitializer(name, settings)); serverBootstrap.childOption(ChannelOption.TCP_NODELAY, TCP_NO_DELAY.get(settings)); serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, TCP_KEEP_ALIVE.get(settings)); final ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.getDefault(settings); if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) { serverBootstrap.childOption(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes())); } final ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.getDefault(settings); if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) { serverBootstrap.childOption(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.bytesAsInt())); } serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator); serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator); final boolean reuseAddress = TCP_REUSE_ADDRESS.get(settings); serverBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress); serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, reuseAddress); serverBootstrap.validate(); serverBootstraps.put(name, serverBootstrap); }
From source file:org.hawkular.metrics.clients.ptrans.PTrans.java
License:Apache License
/** * Starts this PTrans instance. the calling thread will be blocked until another thread calls {@link #stop()}. */// www .j a va 2 s .c om public void start() { LOG.info("Starting ptrans..."); Set<Service> services = configuration.getServices(); List<ChannelFuture> closeFutures = new ArrayList<>(services.size()); if (services.contains(Service.TCP)) { ServerBootstrap serverBootstrap = new ServerBootstrap().group(group, workerGroup) .channel(NioServerSocketChannel.class).localAddress(configuration.getTcpPort()) .childHandler(new TcpChannelInitializer(configuration, forwardingHandler)); ChannelFuture tcpBindFuture = serverBootstrap.bind().syncUninterruptibly(); LOG.info("Server listening on TCP {}", tcpBindFuture.channel().localAddress()); closeFutures.add(tcpBindFuture.channel().closeFuture()); } if (services.contains(Service.UDP)) { Bootstrap udpBootstrap = new Bootstrap().group(group).channel(NioDatagramChannel.class) .localAddress(configuration.getUdpPort()).handler(new UdpChannelInitializer(forwardingHandler)); ChannelFuture udpBindFuture = udpBootstrap.bind().syncUninterruptibly(); LOG.info("Syslogd listening on UDP {}", udpBindFuture.channel().localAddress()); closeFutures.add(udpBindFuture.channel().closeFuture()); } if (services.contains(Service.GANGLIA)) { NetworkInterface mcIf; try { String multicastIfOverride = configuration.getMulticastIfOverride(); if (multicastIfOverride == null) { Inet4Address hostAddr = (Inet4Address) InetAddress.getLocalHost(); mcIf = NetworkInterface.getByInetAddress(hostAddr); } else { mcIf = NetworkInterface.getByName(multicastIfOverride); } } catch (Exception e) { throw new RuntimeException(e); } InetSocketAddress gangliaSocket = new InetSocketAddress(configuration.getGangliaGroup(), configuration.getGangliaPort()); Bootstrap gangliaBootstrap = new Bootstrap().group(group).channel(NioDatagramChannel.class) .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.IP_MULTICAST_IF, mcIf) .localAddress(gangliaSocket) .handler(new GangliaChannelInitializer(configuration, forwardingHandler)); LOG.trace("Ganglia bootstrap is {}", gangliaBootstrap); ChannelFuture gangliaBindFuture = gangliaBootstrap.bind().syncUninterruptibly(); LOG.info("Ganglia listening on UDP {}", gangliaBindFuture.channel().localAddress()); DatagramChannel gangliaChannel = (DatagramChannel) gangliaBindFuture.channel(); gangliaChannel.joinGroup(gangliaSocket, mcIf); LOG.trace("Joined the Ganglia group"); closeFutures.add(gangliaChannel.closeFuture()); } if (services.contains(Service.STATSD)) { Bootstrap statsdBootstrap = new Bootstrap().group(group).channel(NioDatagramChannel.class) .localAddress(configuration.getStatsDport()) .handler(new StatsdChannelInitializer(configuration, forwardingHandler)); ChannelFuture statsdBindFuture = statsdBootstrap.bind().syncUninterruptibly(); LOG.info("Statsd listening on UDP {}", statsdBindFuture.channel().localAddress()); closeFutures.add(statsdBindFuture.channel().closeFuture()); } if (services.contains(Service.COLLECTD)) { Bootstrap collectdBootstrap = new Bootstrap().group(group).channel(NioDatagramChannel.class) .localAddress(configuration.getCollectdPort()) .handler(new CollectdChannelInitializer(configuration, forwardingHandler)); ChannelFuture collectdBindFuture = collectdBootstrap.bind().syncUninterruptibly(); LOG.info("Collectd listening on UDP {}", collectdBindFuture.channel().localAddress()); closeFutures.add(collectdBindFuture.channel().closeFuture()); } LOG.info("ptrans started"); closeFutures.forEach(ChannelFuture::syncUninterruptibly); }
From source file:org.hongxi.whatsmars.remoting.netty.NettyRemotingServer.java
License:Apache License
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(nettyServerConfig.getServerWorkerThreads(), new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override// w ww . j a v a 2 s.com public Thread newThread(Runnable r) { return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet()); } }); ServerBootstrap childHandler = this.serverBootstrap .group(this.eventLoopGroupBoss, this.eventLoopGroupSelector) .channel(useEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_KEEPALIVE, false).childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize()) .childOption(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize()) .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort())) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline() .addLast(defaultEventExecutorGroup, HANDSHAKE_HANDLER_NAME, new HandshakeHandler(TlsSystemConfig.tlsMode)) .addLast(defaultEventExecutorGroup, new NettyEncoder(), new NettyDecoder(), new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), new NettyConnectManageHandler(), new NettyServerHandler()); } }); if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) { childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture sync = this.serverBootstrap.bind().sync(); InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress(); this.port = addr.getPort(); } catch (InterruptedException e1) { throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1); } if (this.channelEventListener != null) { this.nettyEventExecutor.start(); } this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingServer.this.scanResponseTable(); } catch (Throwable e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); }
From source file:org.hornetq.amqp.test.minimalserver.MinimalServer.java
License:Apache License
public synchronized void start(String host, int port, final boolean sasl) throws Exception { this.host = host; this.port = port; this.sasl = sasl; if (channelClazz != null) { // Already started return;/* ww w . ja va 2s .c om*/ } int threadsToUse = Runtime.getRuntime().availableProcessors() * 3; channelClazz = NioServerSocketChannel.class; eventLoopGroup = new NioEventLoopGroup(threadsToUse, new SimpleServerThreadFactory("simple-server", true, Thread.currentThread().getContextClassLoader())); bootstrap = new ServerBootstrap(); bootstrap.group(eventLoopGroup); bootstrap.channel(channelClazz); ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>() { @Override public void initChannel(Channel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast("amqp-handler", new ProtocolDecoder()); } }; bootstrap.childHandler(factory); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.childOption(ChannelOption.SO_REUSEADDR, true); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); bootstrap.childOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT); channelGroup = new DefaultChannelGroup("hornetq-accepted-channels", GlobalEventExecutor.INSTANCE); serverChannelGroup = new DefaultChannelGroup("hornetq-acceptor-channels", GlobalEventExecutor.INSTANCE); startServerChannels(); }
From source file:org.hornetq.core.remoting.impl.netty.NettyAcceptor.java
License:Apache License
public synchronized void start() throws Exception { if (channelClazz != null) { // Already started return;/*from w ww. ja v a 2 s . c o m*/ } if (useInvm) { channelClazz = LocalServerChannel.class; eventLoopGroup = new LocalEventLoopGroup(); } else { int threadsToUse; if (nioRemotingThreads == -1) { // Default to number of cores * 3 threadsToUse = Runtime.getRuntime().availableProcessors() * 3; } else { threadsToUse = this.nioRemotingThreads; } channelClazz = NioServerSocketChannel.class; eventLoopGroup = new NioEventLoopGroup(threadsToUse, new HornetQThreadFactory("hornetq-netty-threads", true, getThisClassLoader())); } bootstrap = new ServerBootstrap(); bootstrap.group(eventLoopGroup); bootstrap.channel(channelClazz); final SSLContext context; if (sslEnabled) { try { if (keyStorePath == null && TransportConstants.DEFAULT_TRUSTSTORE_PROVIDER.equals(keyStoreProvider)) throw new IllegalArgumentException("If \"" + TransportConstants.SSL_ENABLED_PROP_NAME + "\" is true then \"" + TransportConstants.KEYSTORE_PATH_PROP_NAME + "\" must be non-null " + "unless an alternative \"" + TransportConstants.KEYSTORE_PROVIDER_PROP_NAME + "\" has been specified."); context = SSLSupport.createContext(keyStoreProvider, keyStorePath, keyStorePassword, trustStoreProvider, trustStorePath, trustStorePassword); } catch (Exception e) { IllegalStateException ise = new IllegalStateException( "Unable to create NettyAcceptor for " + host + ":" + port); ise.initCause(e); throw ise; } } else { context = null; // Unused } ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>() { @Override public void initChannel(Channel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); if (sslEnabled) { SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(false); if (needClientAuth) engine.setNeedClientAuth(true); // setting the enabled cipher suites resets the enabled protocols so we need // to save the enabled protocols so that after the customer cipher suite is enabled // we can reset the enabled protocols if a customer protocol isn't specified String[] originalProtocols = engine.getEnabledProtocols(); if (enabledCipherSuites != null) { try { engine.setEnabledCipherSuites( SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites)); } catch (IllegalArgumentException e) { HornetQServerLogger.LOGGER.invalidCipherSuite(SSLSupport .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites())); throw e; } } if (enabledProtocols != null) { try { engine.setEnabledProtocols( SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols)); } catch (IllegalArgumentException e) { HornetQServerLogger.LOGGER.invalidProtocol( SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols())); throw e; } } else { engine.setEnabledProtocols(originalProtocols); } SslHandler handler = new SslHandler(engine); pipeline.addLast("ssl", handler); } pipeline.addLast(protocolHandler.getProtocolDecoder()); } }; bootstrap.childHandler(factory); // Bind bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay); if (tcpReceiveBufferSize != -1) { bootstrap.childOption(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize); } if (tcpSendBufferSize != -1) { bootstrap.childOption(ChannelOption.SO_SNDBUF, tcpSendBufferSize); } if (backlog != -1) { bootstrap.option(ChannelOption.SO_BACKLOG, backlog); } bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.childOption(ChannelOption.SO_REUSEADDR, true); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE); channelGroup = new DefaultChannelGroup("hornetq-accepted-channels", GlobalEventExecutor.INSTANCE); serverChannelGroup = new DefaultChannelGroup("hornetq-acceptor-channels", GlobalEventExecutor.INSTANCE); if (httpUpgradeEnabled) { // the channel will be bound by the Web container and hand over after the HTTP Upgrade // handshake is successful } else { startServerChannels(); paused = false; if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putSimpleStringProperty(new SimpleString("factory"), new SimpleString(NettyAcceptorFactory.class.getName())); props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host)); props.putIntProperty(new SimpleString("port"), port); Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STARTED, props); notificationService.sendNotification(notification); } if (batchDelay > 0) { flusher = new BatchFlusher(); batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS); } // TODO: Think about add Version back to netty HornetQServerLogger.LOGGER.startedNettyAcceptor(TransportConstants.NETTY_VERSION, host, port); } }
From source file:org.hornetq.core.remoting.impl.netty.NettyConnector.java
License:Apache License
public synchronized void start() { if (channelClazz != null) { return;/* ww w . j ava2 s. c om*/ } int threadsToUse; if (nioRemotingThreads == -1) { // Default to number of cores * 3 threadsToUse = Runtime.getRuntime().availableProcessors() * 3; } else { threadsToUse = this.nioRemotingThreads; } if (useNioGlobalWorkerPool) { channelClazz = NioSocketChannel.class; group = SharedNioEventLoopGroup.getInstance(threadsToUse); } else { channelClazz = NioSocketChannel.class; group = new NioEventLoopGroup(threadsToUse); } // if we are a servlet wrap the socketChannelFactory if (useServlet) { // TODO: This will be replaced by allow upgrade HTTP connection from Undertow.; } bootstrap = new Bootstrap(); bootstrap.channel(channelClazz); bootstrap.group(group); bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay); if (connectTimeoutMillis != -1) { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis); } if (tcpReceiveBufferSize != -1) { bootstrap.option(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize); } if (tcpSendBufferSize != -1) { bootstrap.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize); } bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.option(ChannelOption.ALLOCATOR, new UnpooledByteBufAllocator(false)); channelGroup = new DefaultChannelGroup("hornetq-connector", GlobalEventExecutor.INSTANCE); final SSLContext context; if (sslEnabled) { try { // HORNETQ-680 - override the server-side config if client-side system properties are set String realKeyStorePath = keyStorePath; String realKeyStoreProvider = keyStoreProvider; String realKeyStorePassword = keyStorePassword; if (System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME) != null) { realKeyStorePath = System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME); } if (System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME) != null) { realKeyStorePassword = System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME); } if (System.getProperty(HORNETQ_KEYSTORE_PROVIDER_PROP_NAME) != null) { realKeyStoreProvider = System.getProperty(HORNETQ_KEYSTORE_PROVIDER_PROP_NAME); } if (System.getProperty(HORNETQ_KEYSTORE_PATH_PROP_NAME) != null) { realKeyStorePath = System.getProperty(HORNETQ_KEYSTORE_PATH_PROP_NAME); } if (System.getProperty(HORNETQ_KEYSTORE_PASSWORD_PROP_NAME) != null) { realKeyStorePassword = System.getProperty(HORNETQ_KEYSTORE_PASSWORD_PROP_NAME); } String realTrustStorePath = trustStorePath; String realTrustStoreProvider = trustStoreProvider; String realTrustStorePassword = trustStorePassword; if (System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME) != null) { realTrustStorePath = System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME); } if (System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME) != null) { realTrustStorePassword = System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME); } if (System.getProperty(HORNETQ_TRUSTSTORE_PROVIDER_PROP_NAME) != null) { realTrustStoreProvider = System.getProperty(HORNETQ_TRUSTSTORE_PROVIDER_PROP_NAME); } if (System.getProperty(HORNETQ_TRUSTSTORE_PATH_PROP_NAME) != null) { realTrustStorePath = System.getProperty(HORNETQ_TRUSTSTORE_PATH_PROP_NAME); } if (System.getProperty(HORNETQ_TRUSTSTORE_PASSWORD_PROP_NAME) != null) { realTrustStorePassword = System.getProperty(HORNETQ_TRUSTSTORE_PASSWORD_PROP_NAME); } context = SSLSupport.createContext(realKeyStoreProvider, realKeyStorePath, realKeyStorePassword, realTrustStoreProvider, realTrustStorePath, realTrustStorePassword); } catch (Exception e) { close(); IllegalStateException ise = new IllegalStateException( "Unable to create NettyConnector for " + host + ":" + port); ise.initCause(e); throw ise; } } else { context = null; // Unused } if (context != null && useServlet) { // TODO: Fix me //bootstrap.setOption("sslContext", context); } bootstrap.handler(new ChannelInitializer<Channel>() { public void initChannel(Channel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); if (sslEnabled && !useServlet) { SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(true); engine.setWantClientAuth(true); // setting the enabled cipher suites resets the enabled protocols so we need // to save the enabled protocols so that after the customer cipher suite is enabled // we can reset the enabled protocols if a customer protocol isn't specified String[] originalProtocols = engine.getEnabledProtocols(); if (enabledCipherSuites != null) { try { engine.setEnabledCipherSuites( SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites)); } catch (IllegalArgumentException e) { HornetQClientLogger.LOGGER.invalidCipherSuite(SSLSupport .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites())); throw e; } } if (enabledProtocols != null) { try { engine.setEnabledProtocols( SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols)); } catch (IllegalArgumentException e) { HornetQClientLogger.LOGGER.invalidProtocol( SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols())); throw e; } } else { engine.setEnabledProtocols(originalProtocols); } SslHandler handler = new SslHandler(engine); pipeline.addLast(handler); } if (httpEnabled) { pipeline.addLast(new HttpRequestEncoder()); pipeline.addLast(new HttpResponseDecoder()); pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE)); pipeline.addLast(new HttpHandler()); } if (httpUpgradeEnabled) { // prepare to handle a HTTP 101 response to upgrade the protocol. final HttpClientCodec httpClientCodec = new HttpClientCodec(); pipeline.addLast(httpClientCodec); pipeline.addLast("http-upgrade", new HttpUpgradeHandler(pipeline, httpClientCodec)); } pipeline.addLast(new HornetQFrameDecoder2()); pipeline.addLast(new HornetQClientChannelHandler(channelGroup, handler, new Listener())); } }); if (batchDelay > 0) { flusher = new BatchFlusher(); batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS); } HornetQClientLogger.LOGGER.debug("Started Netty Connector version " + TransportConstants.NETTY_VERSION); }
From source file:org.iotivity.cloud.base.CoapClient.java
License:Open Source License
public void startClient(final InetSocketAddress inetSocketAddress) throws InterruptedException { try {/*from w ww.ja va 2s .co m*/ Bootstrap b = new Bootstrap(); b.group(connectorGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.SO_REUSEADDR, true); b.handler(initializer); channelFuture = b.connect(inetSocketAddress).sync(); channelFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) throws Exception { Logger.d("Connection status of TCP CoAP CLIENT : " + future.isSuccess()); } }); } finally { } }