List of usage examples for io.netty.channel.socket SocketChannel remoteAddress
@Override
InetSocketAddress remoteAddress();
From source file:com.allanbank.mongodb.netty.NettyTlsConnectionCompletedListenerTest.java
License:Apache License
/** * Test for the/*from ww w . j a v a 2s. com*/ * {@link NettyTlsConnectionCompletedListener#operationComplete} method. * * @throws SocketException * On a test failure. */ @Test public void testOperationComplete() throws SocketException { final InetSocketAddress addr = new InetSocketAddress(12346); final SocketChannel mockChannel = createMock(SocketChannel.class); final SocketConnectionListener mockConnListener = createMock(SocketConnectionListener.class); final SSLEngine mockEngine = createMock(SSLEngine.class); expect(mockChannel.remoteAddress()).andReturn(addr); mockConnListener.connected(addr, mockEngine); expectLastCall(); replay(mockChannel, mockConnListener, mockEngine); final NettyTlsConnectionCompletedListener listener = new NettyTlsConnectionCompletedListener( mockConnListener, mockEngine, mockChannel); listener.operationComplete(null); verify(mockChannel, mockConnListener, mockEngine); }
From source file:com.allanbank.mongodb.netty.NettyTlsConnectionCompletedListenerTest.java
License:Apache License
/** * Test for the//w w w . ja v a2 s. c o m * {@link NettyTlsConnectionCompletedListener#operationComplete} method. * * @throws SocketException * On a test failure. */ @Test public void testOperationCompleteOnError() throws SocketException { final InetSocketAddress addr = new InetSocketAddress(12346); final SocketChannel mockChannel = createMock(SocketChannel.class); final SocketConnectionListener mockConnListener = createMock(SocketConnectionListener.class); final SSLEngine mockEngine = createMock(SSLEngine.class); expect(mockChannel.remoteAddress()).andReturn(addr); mockConnListener.connected(addr, mockEngine); expectLastCall().andThrow(new SocketException("Injected.")); expect(mockChannel.close()).andReturn(null); replay(mockChannel, mockConnListener, mockEngine); final NettyTlsConnectionCompletedListener listener = new NettyTlsConnectionCompletedListener( mockConnListener, mockEngine, mockChannel); listener.operationComplete(null); verify(mockChannel, mockConnListener, mockEngine); }
From source file:com.antsdb.saltedfish.server.mysql.MysqlChannelInitializer.java
License:Open Source License
@Override public void initChannel(SocketChannel ch) throws Exception { _log.trace("channel initialized with remote address {}", ch.remoteAddress()); MysqlServerHandler handler = new MysqlServerHandler(fish); PacketDecoder decoder = new PacketDecoder(handler); ch.pipeline().addLast(decoder, handler); }
From source file:com.datastax.driver.core.utils.SocketChannelMonitor.java
License:Apache License
/** * @param addresses The addresses to include. * @return Open channels matching the given socket addresses. *///from w w w .java 2s . com public Collection<SocketChannel> openChannels(final Collection<InetSocketAddress> addresses) { List<SocketChannel> channels = Lists.newArrayList(matchingChannels(new Predicate<SocketChannel>() { @Override public boolean apply(SocketChannel input) { return input.isOpen() && input.remoteAddress() != null && addresses.contains(input.remoteAddress()); } })); Collections.sort(channels, BY_REMOTE_ADDRESS); return channels; }
From source file:com.foilen.smalltools.net.netty.NettyServer.java
License:Open Source License
/** * Start the server./* ww w. j a va2s . c om*/ * * @param port * the port to listen on (0 for a random port ; get it with {@link #getPort()}) * @param trustedCertificates * (optional) the certificate to trust connections from * @param certificate * (optional) the server's certificate * @param channelHandlerContainers * the channel handlers for the incoming connections */ public void start(final int port, final RSATrustedCertificates trustedCertificates, final RSACertificate certificate, final List<ChannelHandlerContainer> channelHandlerContainers) { AssertTools.assertNull(thread, "Server is already started"); final CountDownLatch countDownLatch = new CountDownLatch(1); thread = new Thread(() -> { try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(NettyCommon.EVENT_LOOP_GROUP, NettyCommon.EVENT_LOOP_GROUP); serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { InetSocketAddress remoteAddress = socketChannel.remoteAddress(); logger.info("Got a connection from {}:{}", remoteAddress.getHostName(), remoteAddress.getPort()); // Add sslCtx if needed if (trustedCertificates != null || certificate != null) { TrustManagerFactory trustManagerFactory = trustedCertificates == null ? null : RSATools.createTrustManagerFactory(trustedCertificates); KeyManagerFactory keyManagerFactory = certificate == null ? null : RSATools.createKeyManagerFactory(certificate); CipherSuiteFilter cipherFilter = IdentityCipherSuiteFilter.INSTANCE; SslContext sslCtx = SslContext.newServerContext(SslProvider.JDK, null, trustManagerFactory, null, null, null, keyManagerFactory, null, cipherFilter, null, 0, 0); SslHandler sslHandler = sslCtx.newHandler(socketChannel.alloc()); if (trustManagerFactory == null) { logger.debug("Will not verify client's identity"); } else { logger.debug("Will verify client's identity"); SSLEngine sslEngine = sslHandler.engine(); sslEngine.setNeedClientAuth(true); } socketChannel.pipeline().addLast(sslHandler); } // Add the channel handlers for (ChannelHandlerContainer channelHandlerContainer : channelHandlerContainers) { socketChannel.pipeline() .addLast(ReflectionTools.instantiate( channelHandlerContainer.getChannelHandlerClass(), channelHandlerContainer.getConstructorParams())); } } }) // .option(ChannelOption.SO_BACKLOG, 128) // .childOption(ChannelOption.SO_KEEPALIVE, true); bindedPort = port; logger.info("Server on port {} is starting...", port); ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); SocketAddress socketAddress = channelFuture.channel().localAddress(); if (socketAddress instanceof InetSocketAddress) { InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress; bindedPort = inetSocketAddress.getPort(); } logger.info("Server on port {} is started", bindedPort); countDownLatch.countDown(); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { logger.info("Server on port {} is interrupted", bindedPort); } finally { countDownLatch.countDown(); } logger.info("Server on port {} is stopped", bindedPort); }); thread.setName("Netty Server-" + bindedPort); thread.start(); try { countDownLatch.await(); } catch (InterruptedException e) { logger.error("Interrupted while waiting for the server to start"); } }
From source file:com.gemstone.gemfire.redis.GemFireRedisServer.java
License:Apache License
/** * Helper method to start the server listening for connections. The * server is bound to the port specified by {@link GemFireRedisServer#serverPort} * //from www. j av a 2 s . c o m * @throws IOException * @throws InterruptedException */ private void startRedisServer() throws IOException, InterruptedException { ThreadFactory selectorThreadFactory = new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("GemFireRedisServer-SelectorThread-" + counter.incrementAndGet()); t.setDaemon(true); return t; } }; ThreadFactory workerThreadFactory = new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("GemFireRedisServer-WorkerThread-" + counter.incrementAndGet()); return t; } }; bossGroup = null; workerGroup = null; Class<? extends ServerChannel> socketClass = null; if (singleThreadPerConnection) { bossGroup = new OioEventLoopGroup(Integer.MAX_VALUE, selectorThreadFactory); workerGroup = new OioEventLoopGroup(Integer.MAX_VALUE, workerThreadFactory); socketClass = OioServerSocketChannel.class; } else { bossGroup = new NioEventLoopGroup(this.numSelectorThreads, selectorThreadFactory); workerGroup = new NioEventLoopGroup(this.numWorkerThreads, workerThreadFactory); socketClass = NioServerSocketChannel.class; } InternalDistributedSystem system = (InternalDistributedSystem) cache.getDistributedSystem(); String pwd = system.getConfig().getRedisPassword(); final byte[] pwdB = Coder.stringToBytes(pwd); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(socketClass).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { if (logger.fineEnabled()) logger.fine("GemFireRedisServer-Connection established with " + ch.remoteAddress()); ChannelPipeline p = ch.pipeline(); p.addLast(ByteToCommandDecoder.class.getSimpleName(), new ByteToCommandDecoder()); p.addLast(ExecutionHandlerContext.class.getSimpleName(), new ExecutionHandlerContext(ch, cache, regionCache, GemFireRedisServer.this, pwdB)); } }).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_RCVBUF, getBufferSize()) .childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, GemFireRedisServer.connectTimeoutMillis) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(new InetSocketAddress(getBindAddress(), serverPort)).sync(); if (this.logger.infoEnabled()) { String logMessage = "GemFireRedisServer started {" + getBindAddress() + ":" + serverPort + "}, Selector threads: " + this.numSelectorThreads; if (this.singleThreadPerConnection) logMessage += ", One worker thread per connection"; else logMessage += ", Worker threads: " + this.numWorkerThreads; this.logger.info(logMessage); } this.serverChannel = f.channel(); }
From source file:com.github.ambry.rest.NettyServerChannelInitializer.java
License:Open Source License
@Override protected void initChannel(SocketChannel ch) throws Exception { // If channel handler implementations are not annotated with @Sharable, Netty creates a new instance of every class // in the pipeline for every connection. // i.e. if there are a 1000 active connections there will be a 1000 NettyMessageProcessor instances. ChannelPipeline pipeline = ch.pipeline(); // connection stats handler to track connection related metrics pipeline.addLast("connectionStatsHandler", connectionStatsHandler); // if SSL is enabled, add an SslHandler before the HTTP codec if (sslFactory != null) { InetSocketAddress peerAddress = ch.remoteAddress(); String peerHost = peerAddress.getHostName(); int peerPort = peerAddress.getPort(); SslHandler sslHandler = new SslHandler( sslFactory.createSSLEngine(peerHost, peerPort, SSLFactory.Mode.SERVER)); pipeline.addLast("sslHandler", sslHandler); }// ww w .j a v a 2 s . com pipeline // for http encoding/decoding. .addLast("codec", new HttpServerCodec(nettyConfig.nettyServerMaxInitialLineLength, nettyConfig.nettyServerMaxHeaderSize, nettyConfig.nettyServerMaxChunkSize)) // for health check request handling .addLast("healthCheckHandler", new HealthCheckHandler(restServerState, nettyMetrics)) // for public access logging .addLast("publicAccessLogHandler", new PublicAccessLogHandler(publicAccessLogger, nettyMetrics)) // for detecting connections that have been idle too long - probably because of an error. .addLast("idleStateHandler", new IdleStateHandler(0, 0, nettyConfig.nettyServerIdleTimeSeconds)) // for safe writing of chunks for responses .addLast("chunker", new ChunkedWriteHandler()) // custom processing class that interfaces with a BlobStorageService. .addLast("processor", new NettyMessageProcessor(nettyMetrics, nettyConfig, requestHandler)); }
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 2 s. c om*/ 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.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. ja v a 2s . c o 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.sohail.alam.http.server.HttpChannelInitializer.java
License:Apache License
@Override protected void initChannel(SocketChannel ch) throws Exception { LOGGER.debug("Http Channel Initialized => Remote Address: {}", ch.remoteAddress()); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("HttpServerCodec", new HttpServerCodec()); pipeline.addLast("ChunkedWriteHandler", new ChunkedWriteHandler()); pipeline.addLast("HttpClientHandler", new HttpClientHandler()); }