Search in sources :

Example 11 with NioSocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.nio.NioSocketChannel in project java-tron by tronprotocol.

the class TronChannelInitializer method initChannel.

@Override
public void initChannel(NioSocketChannel ch) throws Exception {
    try {
        if (isInbound() && channelManager.isRecentlyDisconnected(ch.remoteAddress().getAddress())) {
            // avoid too frequent connection attempts
            logger.info("Drop connection - the same IP was disconnected recently, channel: {}", ch.toString());
            ch.disconnect();
            return;
        }
        final Channel channel = ctx.getBean(PeerConnection.class);
        channel.init(ch.pipeline(), remoteId, peerDiscoveryMode, channelManager, p2pNode);
        if (!peerDiscoveryMode) {
            channelManager.add(channel);
        }
        // limit the size of receiving buffer to 1024
        ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(256 * 1024));
        ch.config().setOption(ChannelOption.SO_RCVBUF, 256 * 1024);
        ch.config().setOption(ChannelOption.SO_BACKLOG, 1024);
        // be aware of channel closing
        ch.closeFuture().addListener((ChannelFutureListener) future -> {
            logger.info("Close channel:" + channel.getNode());
            if (!peerDiscoveryMode) {
                channelManager.notifyDisconnect(channel);
            }
        });
    } catch (Exception e) {
        logger.error("Unexpected error: ", e);
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Logger(org.slf4j.Logger) ChannelInitializer(io.netty.channel.ChannelInitializer) ChannelOption(io.netty.channel.ChannelOption) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) ApplicationContext(org.springframework.context.ApplicationContext) Scope(org.springframework.context.annotation.Scope) PeerConnection(org.tron.core.net.peer.PeerConnection) Component(org.springframework.stereotype.Component) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) NodeImpl(org.tron.core.net.node.NodeImpl) ChannelFutureListener(io.netty.channel.ChannelFutureListener) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator)

Example 12 with NioSocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.nio.NioSocketChannel in project rskj by rsksmart.

the class EthereumChannelInitializerTest method initChannel_AddressIsNotBanned_ShouldNotDisconnect.

@Test
public void initChannel_AddressIsNotBanned_ShouldNotDisconnect() {
    InetSocketAddress address = Objects.requireNonNull(IpUtils.parseAddress("192.168.100.1:5555"));
    PeerScoringManager peerScoringManager = mock(PeerScoringManager.class);
    doReturn(false).when(peerScoringManager).isAddressBanned(eq(address.getAddress()));
    ChannelManager channelManager = mock(ChannelManager.class);
    doReturn(true).when(channelManager).isAddressBlockAvailable(any());
    ChannelPipeline pipeline = mock(ChannelPipeline.class);
    NioSocketChannel channel = mock(NioSocketChannel.class);
    SocketChannelConfig config = mock(SocketChannelConfig.class);
    ChannelFuture channelFuture = mock(ChannelFuture.class);
    doReturn(address).when(channel).remoteAddress();
    doReturn(pipeline).when(channel).pipeline();
    doReturn(config).when(channel).config();
    doReturn(channelFuture).when(channel).closeFuture();
    EthereumChannelInitializer channelInitializer = new EthereumChannelInitializer("", mock(RskSystemProperties.class), channelManager, mock(CompositeEthereumListener.class), mock(ConfigCapabilities.class), mock(NodeManager.class), mock(RskWireProtocol.Factory.class), mock(Eth62MessageFactory.class), mock(StaticMessages.class), peerScoringManager);
    channelInitializer.initChannel(channel);
    verify(channel, never()).disconnect();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) ConfigCapabilities(org.ethereum.net.client.ConfigCapabilities) StaticMessages(org.ethereum.net.message.StaticMessages) Eth62MessageFactory(org.ethereum.net.eth.message.Eth62MessageFactory) Eth62MessageFactory(org.ethereum.net.eth.message.Eth62MessageFactory) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) PeerScoringManager(co.rsk.scoring.PeerScoringManager) NodeManager(org.ethereum.net.NodeManager) CompositeEthereumListener(org.ethereum.listener.CompositeEthereumListener) SocketChannelConfig(io.netty.channel.socket.SocketChannelConfig) RskSystemProperties(co.rsk.config.RskSystemProperties) Test(org.junit.Test)

Example 13 with NioSocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.nio.NioSocketChannel in project ambry by linkedin.

the class Http2MultiplexedChannelPoolTest method closeWaitsForConnectionToBeReleasedBeforeClosingConnectionPool.

/**
 * Connection pool is released first and then close upon h2 pool close.
 */
@Test
public void closeWaitsForConnectionToBeReleasedBeforeClosingConnectionPool() {
    SocketChannel channel = new NioSocketChannel();
    try {
        loopGroup.register(channel).awaitUninterruptibly();
        ChannelPool connectionPool = mock(ChannelPool.class);
        ArgumentCaptor<Promise> releasePromise = ArgumentCaptor.forClass(Promise.class);
        when(connectionPool.release(eq(channel), releasePromise.capture())).thenAnswer(invocation -> {
            Promise<?> promise = releasePromise.getValue();
            promise.setSuccess(null);
            return promise;
        });
        MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null, streamChannelInitializer);
        Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.singleton(record), null, http2ClientConfigForOneConnection, new Http2ClientMetrics(new MetricRegistry()), streamChannelInitializer);
        h2Pool.close();
        InOrder inOrder = Mockito.inOrder(connectionPool);
        inOrder.verify(connectionPool).release(eq(channel), isA(Promise.class));
        inOrder.verify(connectionPool).close();
    } finally {
        channel.close().awaitUninterruptibly();
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) ChannelPool(io.netty.channel.pool.ChannelPool) Promise(io.netty.util.concurrent.Promise) DefaultPromise(io.netty.util.concurrent.DefaultPromise) InOrder(org.mockito.InOrder) MetricRegistry(com.codahale.metrics.MetricRegistry) MultiplexedChannelRecordTest(com.github.ambry.network.http2.MultiplexedChannelRecordTest) Test(org.junit.Test)

Example 14 with NioSocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.nio.NioSocketChannel in project ambry by linkedin.

the class Http2MultiplexedChannelPoolTest method releaseParentChannelsIfPoolIsClosed.

/**
 * Channel acquire should fail if pool is closed.
 */
@Test
public void releaseParentChannelsIfPoolIsClosed() {
    SocketChannel channel = new NioSocketChannel();
    try {
        loopGroup.register(channel).awaitUninterruptibly();
        ChannelPool connectionPool = mock(ChannelPool.class);
        ArgumentCaptor<Promise> releasePromise = ArgumentCaptor.forClass(Promise.class);
        when(connectionPool.release(eq(channel), releasePromise.capture())).thenAnswer(invocation -> {
            Promise<?> promise = releasePromise.getValue();
            promise.setSuccess(null);
            return promise;
        });
        MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null, streamChannelInitializer);
        Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.singleton(record), null, http2ClientConfigForOneConnection, new Http2ClientMetrics(new MetricRegistry()), streamChannelInitializer);
        h2Pool.close();
        InOrder inOrder = Mockito.inOrder(connectionPool);
        inOrder.verify(connectionPool).release(eq(channel), isA(Promise.class));
        inOrder.verify(connectionPool).close();
    } finally {
        channel.close().awaitUninterruptibly();
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) ChannelPool(io.netty.channel.pool.ChannelPool) Promise(io.netty.util.concurrent.Promise) DefaultPromise(io.netty.util.concurrent.DefaultPromise) InOrder(org.mockito.InOrder) MetricRegistry(com.codahale.metrics.MetricRegistry) MultiplexedChannelRecordTest(com.github.ambry.network.http2.MultiplexedChannelRecordTest) Test(org.junit.Test)

Example 15 with NioSocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.nio.NioSocketChannel in project proxyee-down by monkeyWie.

the class HttpDownUtil method getResponse.

/**
 * 取请求响应
 */
public static HttpResponse getResponse(HttpRequest httpRequest, ProxyConfig proxyConfig, SslContext clientSslCtx, NioEventLoopGroup loopGroup) throws Exception {
    final HttpResponse[] httpResponses = new HttpResponse[1];
    CountDownLatch cdl = new CountDownLatch(1);
    HttpRequestInfo requestInfo = (HttpRequestInfo) httpRequest;
    RequestProto requestProto = requestInfo.requestProto();
    Bootstrap bootstrap = new Bootstrap();
    // 注册线程池
    bootstrap.group(loopGroup).channel(// 使用NioSocketChannel来作为连接用的channel类
    NioSocketChannel.class).handler(new ChannelInitializer() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            if (proxyConfig != null) {
                ch.pipeline().addLast(ProxyHandleFactory.build(proxyConfig));
            }
            if (requestProto.getSsl()) {
                ch.pipeline().addLast(clientSslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast("httpCodec", new HttpClientCodec());
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx0, Object msg0) throws Exception {
                    if (msg0 instanceof HttpResponse) {
                        HttpResponse httpResponse = (HttpResponse) msg0;
                        httpResponses[0] = httpResponse;
                        ctx0.channel().close();
                        cdl.countDown();
                    }
                }
            });
        }
    });
    if (proxyConfig != null) {
        // 代理服务器解析DNS和连接
        bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
    }
    ChannelFuture cf = bootstrap.connect(requestProto.getHost(), requestProto.getPort());
    cf.addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            httpRequest.headers().set(HttpHeaderNames.RANGE, "bytes=0-0");
            cf.channel().writeAndFlush(httpRequest);
            if (requestInfo.content() != null) {
                HttpContent content = new DefaultLastHttpContent();
                content.content().writeBytes(requestInfo.content());
                cf.channel().writeAndFlush(content);
            }
        } else {
            cdl.countDown();
        }
    });
    cdl.await(30, TimeUnit.SECONDS);
    if (httpResponses[0] == null) {
        throw new TimeoutException("getResponse timeout");
    }
    return httpResponses[0];
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ProxyConfig(lee.study.proxyee.proxy.ProxyConfig) ProxyHandleFactory(lee.study.proxyee.proxy.ProxyHandleFactory) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) URLDecoder(java.net.URLDecoder) URL(java.net.URL) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) TimeoutException(java.util.concurrent.TimeoutException) RequestProto(lee.study.proxyee.util.ProtoUtil.RequestProto) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) NoopAddressResolverGroup(io.netty.resolver.NoopAddressResolverGroup) TaskInfo(lee.study.down.model.TaskInfo) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Matcher(java.util.regex.Matcher) HttpHeadsInfo(lee.study.down.model.HttpHeadsInfo) HttpVer(lee.study.down.model.HttpRequestInfo.HttpVer) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Map(java.util.Map) HttpContent(io.netty.handler.codec.http.HttpContent) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) SslContext(io.netty.handler.ssl.SslContext) MalformedURLException(java.net.MalformedURLException) HttpRequestInfo(lee.study.down.model.HttpRequestInfo) HttpMethod(io.netty.handler.codec.http.HttpMethod) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) IOException(java.io.IOException) UUID(java.util.UUID) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) CountDownLatch(java.util.concurrent.CountDownLatch) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Closeable(java.io.Closeable) Entry(java.util.Map.Entry) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Pattern(java.util.regex.Pattern) ProtoUtil(lee.study.proxyee.util.ProtoUtil) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpRequestInfo(lee.study.down.model.HttpRequestInfo) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) TimeoutException(java.util.concurrent.TimeoutException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) RequestProto(lee.study.proxyee.util.ProtoUtil.RequestProto) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)17 Test (org.junit.Test)8 Bootstrap (io.netty.bootstrap.Bootstrap)5 Channel (io.netty.channel.Channel)5 ChannelFuture (io.netty.channel.ChannelFuture)5 ChannelInitializer (io.netty.channel.ChannelInitializer)4 ChannelPipeline (io.netty.channel.ChannelPipeline)4 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)4 ChannelPool (io.netty.channel.pool.ChannelPool)4 InetSocketAddress (java.net.InetSocketAddress)4 MetricRegistry (com.codahale.metrics.MetricRegistry)3 MultiplexedChannelRecordTest (com.github.ambry.network.http2.MultiplexedChannelRecordTest)3 SocketChannel (io.netty.channel.socket.SocketChannel)3 SocketChannelConfig (io.netty.channel.socket.SocketChannelConfig)3 DefaultPromise (io.netty.util.concurrent.DefaultPromise)3 RskSystemProperties (co.rsk.config.RskSystemProperties)2 PeerScoringManager (co.rsk.scoring.PeerScoringManager)2 ChannelFutureListener (io.netty.channel.ChannelFutureListener)2 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)2 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)2