List of usage examples for io.netty.channel ChannelOption SO_BACKLOG
ChannelOption SO_BACKLOG
To view the source code for io.netty.channel ChannelOption SO_BACKLOG.
Click Source Link
From source file:org.apache.activemq.core.remoting.impl.netty.NettyAcceptor.java
License:Apache License
public synchronized void start() throws Exception { if (channelClazz != null) { // Already started return;//from www. j av a2s . co 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 ActiveMQThreadFactory("activemq-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) { ActiveMQServerLogger.LOGGER.invalidCipherSuite(SSLSupport .parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites())); throw e; } } if (enabledProtocols != null) { try { engine.setEnabledProtocols( SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols)); } catch (IllegalArgumentException e) { ActiveMQServerLogger.LOGGER.invalidProtocol( SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols())); throw e; } } else { engine.setEnabledProtocols(originalProtocols); } // Strip "SSLv3" from the current enabled protocols to address the POODLE exploit. // This recommendation came from http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html String[] protocols = engine.getEnabledProtocols(); Set<String> set = new HashSet<>(); for (String s : protocols) { if (s.equals("SSLv3") || s.equals("SSLv2Hello")) { ActiveMQServerLogger.LOGGER.disallowedProtocol(s); continue; } set.add(s); } engine.setEnabledProtocols(set.toArray(new String[0])); 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("activemq-accepted-channels", GlobalEventExecutor.INSTANCE); serverChannelGroup = new DefaultChannelGroup("activemq-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); } ActiveMQServerLogger.LOGGER.startedNettyAcceptor(TransportConstants.NETTY_VERSION, host, port); } }
From source file:org.apache.camel.component.netty4.SingleTCPNettyServerBootstrapFactory.java
License:Apache License
protected void startServerBootstrap() { // prefer using explicit configured thread pools EventLoopGroup bg = configuration.getBossGroup(); EventLoopGroup wg = configuration.getWorkerGroup(); if (bg == null) { // create new pool which we should shutdown when stopping as its not shared bossGroup = new NettyServerBossPoolBuilder().withBossCount(configuration.getBossCount()) .withName("NettyServerTCPBoss").build(); bg = bossGroup;//w ww.j a va 2s. com } if (wg == null) { // create new pool which we should shutdown when stopping as its not shared workerGroup = new NettyWorkerPoolBuilder().withWorkerCount(configuration.getWorkerCount()) .withName("NettyServerTCPWorker").build(); wg = workerGroup; } //channelFactory = new NioServerSocketChannelFactory(bg, wg); serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bg, wg).channel(NioServerSocketChannel.class); serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive()); serverBootstrap.childOption(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay()); serverBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress()); serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress()); serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout()); if (configuration.getBacklog() > 0) { serverBootstrap.option(ChannelOption.SO_BACKLOG, configuration.getBacklog()); } // TODO set any additional netty options and child options /*if (configuration.getOptions() != null) { for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) { serverBootstrap.setOption(entry.getKey(), entry.getValue()); } }*/ // set the pipeline factory, which creates the pipeline for each newly created channels serverBootstrap.childHandler(pipelineFactory); LOG.debug("Created ServerBootstrap {}", serverBootstrap); LOG.info("ServerBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort()); ChannelFuture channelFutrue = serverBootstrap .bind(new InetSocketAddress(configuration.getHost(), configuration.getPort())); channelFutrue.awaitUninterruptibly(); channel = channelFutrue.channel(); // to keep track of all channels in use allChannels.add(channel); }
From source file:org.apache.camel.component.netty4.SingleUDPNettyServerBootstrapFactory.java
License:Apache License
protected void startServerBootstrap() throws Exception { // create non-shared worker pool EventLoopGroup wg = configuration.getWorkerGroup(); if (wg == null) { // create new pool which we should shutdown when stopping as its not shared workerGroup = new NettyWorkerPoolBuilder().withWorkerCount(configuration.getWorkerCount()) .withName("NettyServerTCPWorker").build(); wg = workerGroup;// ww w.j ava 2 s. com } Bootstrap bootstrap = new Bootstrap(); bootstrap.group(wg).channel(NioDatagramChannel.class); // We cannot set the child option here bootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress()); bootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize()); bootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize()); bootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast()); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout()); // TODO need to find the right setting of below option // only set this if user has specified /* if (configuration.getReceiveBufferSizePredictor() > 0) { bootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(configuration.getReceiveBufferSizePredictor())); }*/ if (configuration.getBacklog() > 0) { bootstrap.option(ChannelOption.SO_BACKLOG, configuration.getBacklog()); } //TODO need to check the additional netty options /* if (configuration.getOptions() != null) { for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) { connectionlessBootstrap.setOption(entry.getKey(), entry.getValue()); } }*/ LOG.debug("Created ConnectionlessBootstrap {}", bootstrap); // set the pipeline factory, which creates the pipeline for each newly created channels bootstrap.handler(pipelineFactory); InetSocketAddress hostAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort()); SubnetUtils multicastSubnet = new SubnetUtils(MULTICAST_SUBNET); if (multicastSubnet.getInfo().isInRange(configuration.getHost())) { ChannelFuture channelFuture = bootstrap.bind(hostAddress); channelFuture.awaitUninterruptibly(); channel = channelFuture.channel(); DatagramChannel datagramChannel = (DatagramChannel) channel; String networkInterface = configuration.getNetworkInterface() == null ? LOOPBACK_INTERFACE : configuration.getNetworkInterface(); multicastNetworkInterface = NetworkInterface.getByName(networkInterface); ObjectHelper.notNull(multicastNetworkInterface, "No network interface found for '" + networkInterface + "'."); LOG.info("ConnectionlessBootstrap joining {}:{} using network interface: {}", new Object[] { configuration.getHost(), configuration.getPort(), multicastNetworkInterface.getName() }); datagramChannel.joinGroup(hostAddress, multicastNetworkInterface).syncUninterruptibly(); allChannels.add(datagramChannel); } else { LOG.info("ConnectionlessBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort()); ChannelFuture channelFuture = bootstrap.bind(hostAddress); channelFuture.awaitUninterruptibly(); channel = channelFuture.channel(); allChannels.add(channel); } }
From source file:org.apache.drill.exec.rpc.BasicServer.java
License:Apache License
public BasicServer(final RpcConfig rpcMapping, ByteBufAllocator alloc, EventLoopGroup eventLoopGroup) { super(rpcMapping); this.eventLoopGroup = eventLoopGroup; b = new ServerBootstrap().channel(TransportCheck.getServerSocketChannel()) .option(ChannelOption.SO_BACKLOG, 1000).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30 * 1000) .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_RCVBUF, 1 << 17).option(ChannelOption.SO_SNDBUF, 1 << 17) .group(eventLoopGroup) // .childOption(ChannelOption.ALLOCATOR, alloc) // .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/*w w w .j a v a2 s . c om*/ protected void initChannel(SocketChannel ch) throws Exception { // logger.debug("Starting initialization of server connection."); C connection = initRemoteConnection(ch); ch.closeFuture().addListener(getCloseHandler(ch, connection)); final ChannelPipeline pipe = ch.pipeline(); pipe.addLast("protocol-decoder", getDecoder(connection.getAllocator(), getOutOfMemoryHandler())); pipe.addLast("message-decoder", new RpcDecoder("s-" + rpcConfig.getName())); pipe.addLast("protocol-encoder", new RpcEncoder("s-" + rpcConfig.getName())); pipe.addLast("handshake-handler", getHandshakeHandler(connection)); if (rpcMapping.hasTimeout()) { pipe.addLast(TIMEOUT_HANDLER, new LogggingReadTimeoutHandler(connection, rpcMapping.getTimeout())); } pipe.addLast("message-handler", new InboundHandler(connection)); pipe.addLast("exception-handler", new RpcExceptionHandler<C>(connection)); connect = true; // logger.debug("Server connection initialization completed."); } }); // if(TransportCheck.SUPPORTS_EPOLL){ // b.option(EpollChannelOption.SO_REUSEPORT, true); // // } }
From source file:org.apache.flink.runtime.io.network.netty.NettyServer.java
License:Apache License
void init(final NettyProtocol protocol, NettyBufferPool nettyBufferPool) throws IOException { checkState(bootstrap == null, "Netty server has already been initialized."); long start = System.currentTimeMillis(); bootstrap = new ServerBootstrap(); // -------------------------------------------------------------------- // Transport-specific configuration // -------------------------------------------------------------------- switch (config.getTransportType()) { case NIO:// w ww . j a v a 2 s .c o m initNioBootstrap(); break; case EPOLL: initEpollBootstrap(); break; case AUTO: if (Epoll.isAvailable()) { initEpollBootstrap(); LOG.info("Transport type 'auto': using EPOLL."); } else { initNioBootstrap(); LOG.info("Transport type 'auto': using NIO."); } } // -------------------------------------------------------------------- // Configuration // -------------------------------------------------------------------- // Server bind address bootstrap.localAddress(config.getServerAddress(), config.getServerPort()); // Pooled allocators for Netty's ByteBuf instances bootstrap.option(ChannelOption.ALLOCATOR, nettyBufferPool); bootstrap.childOption(ChannelOption.ALLOCATOR, nettyBufferPool); if (config.getServerConnectBacklog() > 0) { bootstrap.option(ChannelOption.SO_BACKLOG, config.getServerConnectBacklog()); } // Receive and send buffer size int receiveAndSendBufferSize = config.getSendAndReceiveBufferSize(); if (receiveAndSendBufferSize > 0) { bootstrap.childOption(ChannelOption.SO_SNDBUF, receiveAndSendBufferSize); bootstrap.childOption(ChannelOption.SO_RCVBUF, receiveAndSendBufferSize); } // Low and high water marks for flow control bootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, config.getMemorySegmentSize() + 1); bootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 2 * config.getMemorySegmentSize()); // -------------------------------------------------------------------- // Child channel pipeline for accepted connections // -------------------------------------------------------------------- bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { channel.pipeline().addLast(protocol.getServerChannelHandlers()); } }); // -------------------------------------------------------------------- // Start Server // -------------------------------------------------------------------- bindFuture = bootstrap.bind().syncUninterruptibly(); long end = System.currentTimeMillis(); LOG.info("Successful initialization (took {} ms). Listening on SocketAddress {}.", (end - start), bindFuture.channel().localAddress().toString()); }
From source file:org.apache.giraph.comm.netty.NettyServer.java
License:Apache License
/** * Start the server with the appropriate port *//*from ww w .j a v a2 s . c o m*/ public void start() { bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, tcpBacklog) .option(ChannelOption.ALLOCATOR, conf.getNettyAllocator()) .childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_SNDBUF, sendBufferSize) .childOption(ChannelOption.SO_RCVBUF, receiveBufferSize) .childOption(ChannelOption.ALLOCATOR, conf.getNettyAllocator()) .childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(receiveBufferSize / 4, receiveBufferSize, receiveBufferSize)); /** * Pipeline setup: depends on whether configured to use authentication * or not. */ bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { /*if_not[HADOOP_NON_SECURE]*/ if (conf.authenticate()) { LOG.info("start: Will use Netty pipeline with " + "authentication and authorization of clients."); // After a client authenticates, the two authentication-specific // pipeline components SaslServerHandler and ResponseEncoder are // removed, leaving the pipeline the same as in the non-authenticated // configuration except for the presence of the Authorize component. PipelineUtils.addLastWithExecutorCheck("serverInboundByteCounter", inByteCounter, handlerToUseExecutionGroup, executionGroup, ch); if (conf.doCompression()) { PipelineUtils.addLastWithExecutorCheck("compressionDecoder", conf.getNettyCompressionDecoder(), handlerToUseExecutionGroup, executionGroup, ch); } PipelineUtils.addLastWithExecutorCheck("serverOutboundByteCounter", outByteCounter, handlerToUseExecutionGroup, executionGroup, ch); if (conf.doCompression()) { PipelineUtils.addLastWithExecutorCheck("compressionEncoder", conf.getNettyCompressionEncoder(), handlerToUseExecutionGroup, executionGroup, ch); } PipelineUtils.addLastWithExecutorCheck("requestFrameDecoder", new LengthFieldBasedFrameDecoder(1024 * 1024 * 1024, 0, 4, 0, 4), handlerToUseExecutionGroup, executionGroup, ch); PipelineUtils.addLastWithExecutorCheck("requestDecoder", new RequestDecoder(conf, inByteCounter), handlerToUseExecutionGroup, executionGroup, ch); // Removed after authentication completes: PipelineUtils.addLastWithExecutorCheck("saslServerHandler", saslServerHandlerFactory.newHandler(conf), handlerToUseExecutionGroup, executionGroup, ch); PipelineUtils.addLastWithExecutorCheck("authorizeServerHandler", new AuthorizeServerHandler(), handlerToUseExecutionGroup, executionGroup, ch); PipelineUtils.addLastWithExecutorCheck( "requestServerHandler", requestServerHandlerFactory.newHandler(workerRequestReservedMap, conf, myTaskInfo, exceptionHandler), handlerToUseExecutionGroup, executionGroup, ch); // Removed after authentication completes: PipelineUtils.addLastWithExecutorCheck("responseEncoder", new ResponseEncoder(), handlerToUseExecutionGroup, executionGroup, ch); } else { LOG.info("start: Using Netty without authentication."); /*end[HADOOP_NON_SECURE]*/ // Store all connected channels in order to ensure that we can close // them on stop(), or else stop() may hang waiting for the // connections to close on their own ch.pipeline().addLast("connectedChannels", new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { accepted.add(ctx.channel()); ctx.fireChannelActive(); } }); PipelineUtils.addLastWithExecutorCheck("serverInboundByteCounter", inByteCounter, handlerToUseExecutionGroup, executionGroup, ch); if (conf.doCompression()) { PipelineUtils.addLastWithExecutorCheck("compressionDecoder", conf.getNettyCompressionDecoder(), handlerToUseExecutionGroup, executionGroup, ch); } PipelineUtils.addLastWithExecutorCheck("serverOutboundByteCounter", outByteCounter, handlerToUseExecutionGroup, executionGroup, ch); if (conf.doCompression()) { PipelineUtils.addLastWithExecutorCheck("compressionEncoder", conf.getNettyCompressionEncoder(), handlerToUseExecutionGroup, executionGroup, ch); } PipelineUtils.addLastWithExecutorCheck("requestFrameDecoder", new LengthFieldBasedFrameDecoder(1024 * 1024 * 1024, 0, 4, 0, 4), handlerToUseExecutionGroup, executionGroup, ch); PipelineUtils.addLastWithExecutorCheck("requestDecoder", new RequestDecoder(conf, inByteCounter), handlerToUseExecutionGroup, executionGroup, ch); PipelineUtils.addLastWithExecutorCheck( "requestServerHandler", requestServerHandlerFactory.newHandler(workerRequestReservedMap, conf, myTaskInfo, exceptionHandler), handlerToUseExecutionGroup, executionGroup, ch); /*if_not[HADOOP_NON_SECURE]*/ } /*end[HADOOP_NON_SECURE]*/ } }); int taskId = conf.getTaskPartition(); int numTasks = conf.getInt("mapred.map.tasks", 1); // Number of workers + 1 for master int numServers = conf.getInt(GiraphConstants.MAX_WORKERS, numTasks) + 1; int portIncrementConstant = (int) Math.pow(10, Math.ceil(Math.log10(numServers))); int bindPort = GiraphConstants.IPC_INITIAL_PORT.get(conf) + taskId; int bindAttempts = 0; final int maxIpcPortBindAttempts = MAX_IPC_PORT_BIND_ATTEMPTS.get(conf); final boolean failFirstPortBindingAttempt = GiraphConstants.FAIL_FIRST_IPC_PORT_BIND_ATTEMPT.get(conf); // Simple handling of port collisions on the same machine while // preserving debugability from the port number alone. // Round up the max number of workers to the next power of 10 and use // it as a constant to increase the port number with. while (bindAttempts < maxIpcPortBindAttempts) { this.myAddress = new InetSocketAddress(localHostname, bindPort); if (failFirstPortBindingAttempt && bindAttempts == 0) { if (LOG.isInfoEnabled()) { LOG.info("start: Intentionally fail first " + "binding attempt as giraph.failFirstIpcPortBindAttempt " + "is true, port " + bindPort); } ++bindAttempts; bindPort += portIncrementConstant; continue; } try { ChannelFuture f = bootstrap.bind(myAddress).sync(); accepted.add(f.channel()); break; } catch (InterruptedException e) { throw new IllegalStateException(e); // CHECKSTYLE: stop IllegalCatchCheck } catch (Exception e) { // CHECKSTYLE: resume IllegalCatchCheck LOG.warn("start: Likely failed to bind on attempt " + bindAttempts + " to port " + bindPort, e.getCause()); ++bindAttempts; bindPort += portIncrementConstant; } } if (bindAttempts == maxIpcPortBindAttempts || myAddress == null) { throw new IllegalStateException( "start: Failed to start NettyServer with " + bindAttempts + " attempts"); } if (LOG.isInfoEnabled()) { LOG.info("start: Started server " + "communication server: " + myAddress + " with up to " + maxPoolSize + " threads on bind attempt " + bindAttempts + " with sendBufferSize = " + sendBufferSize + " receiveBufferSize = " + receiveBufferSize); } }
From source file:org.apache.hive.spark.client.rpc.RpcServer.java
License:Apache License
public RpcServer(Map<String, String> mapConf) throws IOException, InterruptedException { this.config = new RpcConfiguration(mapConf); this.group = new NioEventLoopGroup(this.config.getRpcThreadCount(), new ThreadFactoryBuilder().setNameFormat("RPC-Handler-%d").setDaemon(true).build()); this.channel = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from w w w . j ava 2s.c o m*/ public void initChannel(SocketChannel ch) throws Exception { SaslServerHandler saslHandler = new SaslServerHandler(config); final Rpc newRpc = Rpc.createServer(saslHandler, config, ch, group); saslHandler.rpc = newRpc; Runnable cancelTask = new Runnable() { @Override public void run() { LOG.warn("Timed out waiting for hello from client."); newRpc.close(); } }; saslHandler.cancelTask = group.schedule(cancelTask, RpcServer.this.config.getServerConnectTimeoutMs(), TimeUnit.MILLISECONDS); } }).option(ChannelOption.SO_BACKLOG, 1).option(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.SO_KEEPALIVE, true).bind(0).sync().channel(); this.port = ((InetSocketAddress) channel.localAddress()).getPort(); this.pendingClients = Maps.newConcurrentMap(); this.address = this.config.getServerAddress(); }
From source file:org.apache.kerby.kerberos.kdc.impl.NettyKdcNetwork.java
License:Apache License
private void doStart() throws Exception { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(createChannelInitializer()); // Start the server. b.bind(tcpAddress.getPort());/*from www . ja v a 2 s . com*/ if (udpAddress != null) { startUDPServer(); } }
From source file:org.apache.qpid.jms.transports.netty.NettyServer.java
License:Apache License
public void start() throws Exception { if (started.compareAndSet(false, true)) { // Configure the server. bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); ServerBootstrap server = new ServerBootstrap(); server.group(bossGroup, workerGroup); server.channel(NioServerSocketChannel.class); server.option(ChannelOption.SO_BACKLOG, 100); server.handler(new LoggingHandler(LogLevel.INFO)); server.childHandler(new ChannelInitializer<Channel>() { @Override/*from w w w . ja va2s . c o m*/ public void initChannel(Channel ch) throws Exception { if (options instanceof TransportSslOptions) { TransportSslOptions sslOptions = (TransportSslOptions) options; SSLContext context = TransportSupport.createSslContext(sslOptions); SSLEngine engine = TransportSupport.createSslEngine(context, sslOptions); engine.setUseClientMode(false); engine.setNeedClientAuth(needClientAuth); sslHandler = new SslHandler(engine); ch.pipeline().addLast(sslHandler); } if (webSocketServer) { ch.pipeline().addLast(new HttpServerCodec()); ch.pipeline().addLast(new HttpObjectAggregator(65536)); ch.pipeline().addLast(new WebSocketServerProtocolHandler(getWebSocketPath(), "amqp", true)); } ch.pipeline().addLast(new NettyServerOutboundHandler()); ch.pipeline().addLast(new NettyServerInboundHandler()); ch.pipeline().addLast(getServerHandler()); } }); // Start the server. serverChannel = server.bind(getServerPort()).sync().channel(); } }
From source file:org.apache.reef.wake.remote.transport.netty.NettyMessagingTransport.java
License:Apache License
/** * Constructs a messaging transport//from w w w . j a v a 2s . c o m * * @param hostAddress the server host address * @param port the server listening port; when it is 0, randomly assign a port number * @param clientStage the client-side stage that handles transport events * @param serverStage the server-side stage that handles transport events * @param numberOfTries the number of tries of connection * @param retryTimeout the timeout of reconnection */ public NettyMessagingTransport(final String hostAddress, int port, final EStage<TransportEvent> clientStage, final EStage<TransportEvent> serverStage, final int numberOfTries, final int retryTimeout) { if (port < 0) { throw new RemoteRuntimeException("Invalid server port: " + port); } this.numberOfTries = numberOfTries; this.retryTimeout = retryTimeout; this.clientEventListener = new NettyClientEventListener(this.addrToLinkRefMap, clientStage); this.serverEventListener = new NettyServerEventListener(this.addrToLinkRefMap, serverStage); this.serverBossGroup = new NioEventLoopGroup(SERVER_BOSS_NUM_THREADS, new DefaultThreadFactory(CLASS_NAME + "ServerBoss")); this.serverWorkerGroup = new NioEventLoopGroup(SERVER_WORKER_NUM_THREADS, new DefaultThreadFactory(CLASS_NAME + "ServerWorker")); this.clientWorkerGroup = new NioEventLoopGroup(CLIENT_WORKER_NUM_THREADS, new DefaultThreadFactory(CLASS_NAME + "ClientWorker")); this.clientBootstrap = new Bootstrap(); this.clientBootstrap.group(this.clientWorkerGroup).channel(NioSocketChannel.class) .handler(new NettyChannelInitializer(new NettyDefaultChannelHandlerFactory("client", this.clientChannelGroup, this.clientEventListener))) .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_KEEPALIVE, true); this.serverBootstrap = new ServerBootstrap(); this.serverBootstrap.group(this.serverBossGroup, this.serverWorkerGroup) .channel(NioServerSocketChannel.class) .childHandler(new NettyChannelInitializer(new NettyDefaultChannelHandlerFactory("server", this.serverChannelGroup, this.serverEventListener))) .option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.SO_KEEPALIVE, true); LOG.log(Level.FINE, "Binding to {0}", port); Channel acceptor = null; try { if (port > 0) { acceptor = this.serverBootstrap.bind(new InetSocketAddress(hostAddress, port)).sync().channel(); } else { while (acceptor == null) { port = randPort.nextInt(PORT_START) + PORT_RANGE; LOG.log(Level.FINEST, "Try port {0}", port); try { acceptor = this.serverBootstrap.bind(new InetSocketAddress(hostAddress, port)).sync() .channel(); } catch (final Exception ex) { if (ex instanceof BindException) { LOG.log(Level.FINEST, "The port {0} is already bound. Try again", port); } else { throw ex; } } } } } catch (final Exception ex) { final RuntimeException transportException = new TransportRuntimeException( "Cannot bind to port " + port); LOG.log(Level.SEVERE, "Cannot bind to port " + port, ex); this.clientWorkerGroup.shutdownGracefully(); this.serverBossGroup.shutdownGracefully(); this.serverWorkerGroup.shutdownGracefully(); throw transportException; } this.acceptor = acceptor; this.serverPort = port; this.localAddress = new InetSocketAddress(hostAddress, this.serverPort); LOG.log(Level.FINE, "Starting netty transport socket address: {0}", this.localAddress); }