Search in sources :

Example 6 with NioSocketChannel

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

the class NettyClient method main.

public static void main(String[] args) throws InterruptedException {
    // 1、创建客户端启动类
    Bootstrap client = new Bootstrap();
    // 2、定义线程组,处理读写和链接事件,没有了accept事件
    EventLoopGroup group = new NioEventLoopGroup();
    client.group(group);
    // 3、绑定客户端通道
    client.channel(NioSocketChannel.class);
    // 4、给NIoSocketChannel初始化handler, 处理读写事件
    client.handler(new ChannelInitializer<NioSocketChannel>() {

        @Override
        protected void initChannel(NioSocketChannel ch) throws Exception {
            // 字符串编码器,一定要加在SimpleClientHandler 的上面
            ch.pipeline().addLast(new StringEncoder());
            // 基于分隔符的帧解码器
            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()[0]));
            // 通道入站处理器(用来处理服务端返回的数据)
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (msg instanceof ByteBuf) {
                        String value = ((ByteBuf) msg).toString(Charset.defaultCharset());
                        System.out.println("Server=>" + value);
                    }
                    // 把客户端的通道关闭
                    ctx.channel().close();
                }
            });
        }
    });
    // 5、连接服务器
    ChannelFuture future = client.connect("localhost", 8080).sync();
    // 6、推送数据
    for (int i = 0; i < 5; i++) {
        future.channel().writeAndFlush("hello-" + i + "\r\n");
    }
    // 
    future.channel().closeFuture().sync();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DelimiterBasedFrameDecoder(io.netty.handler.codec.DelimiterBasedFrameDecoder) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) StringEncoder(io.netty.handler.codec.string.StringEncoder) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 7 with NioSocketChannel

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

the class ShuffleHandler method initPipeline.

private void initPipeline(ServerBootstrap bootstrap, Configuration conf) throws Exception {
    SHUFFLE = getShuffle(conf);
    // TODO Setup SSL Shuffle
    // if (conf.getBoolean(MRConfig.SHUFFLE_SSL_ENABLED_KEY,
    // MRConfig.SHUFFLE_SSL_ENABLED_DEFAULT)) {
    // LOG.info("Encrypted shuffle is enabled.");
    // sslFactory = new SSLFactory(SSLFactory.Mode.SERVER, conf);
    // sslFactory.init();
    // }
    ChannelInitializer<NioSocketChannel> channelInitializer = new ChannelInitializer<NioSocketChannel>() {

        @Override
        public void initChannel(NioSocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (sslFactory != null) {
                pipeline.addLast("ssl", new SslHandler(sslFactory.createSSLEngine()));
            }
            pipeline.addLast("decoder", new HttpRequestDecoder());
            pipeline.addLast("aggregator", new HttpObjectAggregator(1 << 16));
            pipeline.addLast("encoder", new HttpResponseEncoder());
            pipeline.addLast("chunking", new ChunkedWriteHandler());
            pipeline.addLast("shuffle", SHUFFLE);
            pipeline.addLast("idle", new IdleStateHandler(0, connectionKeepAliveTimeOut, 0));
            pipeline.addLast(TIMEOUT_HANDLER, new TimeoutHandler());
        }
    };
    bootstrap.childHandler(channelInitializer);
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler)

Example 8 with NioSocketChannel

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

the class EthereumChannelInitializer method initChannel.

@Override
public void initChannel(NioSocketChannel ch) {
    try {
        logger.info("Open {} connection, channel: {}", isInbound() ? "inbound" : "outbound", ch);
        if (isInbound()) {
            InetAddress address = ch.remoteAddress().getAddress();
            if (channelManager.isRecentlyDisconnected(address)) {
                // avoid too frequent connection attempts
                logger.info("Drop connection - the same IP was disconnected recently, channel: {}", ch);
                ch.disconnect();
                return;
            } else if (!channelManager.isAddressBlockAvailable(address)) {
                // avoid too many connection from same block address
                logger.info("IP range is full, IP {} is not accepted for new connection", address);
                ch.disconnect();
                return;
            } else if (peerScoringManager.isAddressBanned(address)) {
                // avoid connections to banned addresses
                logger.info("Drop connection - the address is banned, channel: {}", address);
                ch.disconnect();
                return;
            }
        }
        MessageQueue messageQueue = new MessageQueue();
        P2pHandler p2pHandler = new P2pHandler(ethereumListener, messageQueue, config.getPeerP2PPingInterval());
        MessageCodec messageCodec = new MessageCodec(ethereumListener, config);
        HandshakeHandler handshakeHandler = new HandshakeHandler(config, peerScoringManager, p2pHandler, messageCodec, configCapabilities);
        Channel channel = new Channel(messageQueue, messageCodec, nodeManager, rskWireProtocolFactory, eth62MessageFactory, staticMessages, remoteId);
        ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(config.peerChannelReadTimeout(), TimeUnit.SECONDS));
        ch.pipeline().addLast("handshakeHandler", handshakeHandler);
        handshakeHandler.setRemoteId(remoteId, channel);
        messageCodec.setChannel(channel);
        messageQueue.setChannel(channel);
        messageCodec.setP2pMessageFactory(new P2pMessageFactory());
        channelManager.add(channel);
        // limit the size of receiving buffer to 1024
        SocketChannelConfig channelConfig = ch.config();
        channelConfig.setRecvByteBufAllocator(new FixedRecvByteBufAllocator(16_777_216));
        channelConfig.setOption(ChannelOption.SO_RCVBUF, 16_777_216);
        channelConfig.setOption(ChannelOption.SO_BACKLOG, 1024);
        // be aware of channel closing
        ch.closeFuture().addListener(future -> channelManager.notifyDisconnect(channel));
    } catch (Exception e) {
        logger.error("Unexpected error: ", e);
    }
}
Also used : HandshakeHandler(org.ethereum.net.rlpx.HandshakeHandler) MessageQueue(org.ethereum.net.MessageQueue) P2pHandler(org.ethereum.net.p2p.P2pHandler) SocketChannelConfig(io.netty.channel.socket.SocketChannelConfig) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) P2pMessageFactory(org.ethereum.net.p2p.P2pMessageFactory) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) MessageCodec(org.ethereum.net.rlpx.MessageCodec) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) InetAddress(java.net.InetAddress)

Example 9 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_AddressIsBanned_ShouldDisconnect.

@Test
public void initChannel_AddressIsBanned_ShouldDisconnect() {
    InetSocketAddress address = Objects.requireNonNull(IpUtils.parseAddress("192.168.100.1:5555"));
    PeerScoringManager peerScoringManager = mock(PeerScoringManager.class);
    doReturn(true).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, atLeastOnce()).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 10 with NioSocketChannel

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

the class Http2MultiplexedChannelPoolTest method interruptDuringClosePreservesFlag.

/**
 * Interrupt flag is preserved if pool close is interrupted.
 */
@Test(timeout = 5_000)
public void interruptDuringClosePreservesFlag() throws InterruptedException {
    SocketChannel channel = new NioSocketChannel();
    try {
        loopGroup.register(channel).awaitUninterruptibly();
        Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next());
        channelPromise.setSuccess(channel);
        ChannelPool connectionPool = mock(ChannelPool.class);
        Promise<Void> releasePromise = Mockito.spy(new DefaultPromise<>(loopGroup.next()));
        when(connectionPool.release(eq(channel))).thenReturn(releasePromise);
        MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null, streamChannelInitializer);
        Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.singleton(record), null, http2ClientConfigForOneConnection, new Http2ClientMetrics(new MetricRegistry()), streamChannelInitializer);
        CompletableFuture<Boolean> interrupteFlagPreserved = new CompletableFuture<>();
        Thread t = new Thread(() -> {
            try {
                h2Pool.close();
            } catch (Exception e) {
                if (e.getCause() instanceof InterruptedException && Thread.currentThread().isInterrupted()) {
                    interrupteFlagPreserved.complete(true);
                }
            }
        });
        t.start();
        t.interrupt();
        t.join();
        assertTrue(interrupteFlagPreserved.join());
    } finally {
        channel.close().awaitUninterruptibly();
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) ChannelPool(io.netty.channel.pool.ChannelPool) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) Http2StreamChannel(io.netty.handler.codec.http2.Http2StreamChannel) MetricRegistry(com.codahale.metrics.MetricRegistry) IOException(java.io.IOException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) CompletableFuture(java.util.concurrent.CompletableFuture) DefaultPromise(io.netty.util.concurrent.DefaultPromise) MultiplexedChannelRecordTest(com.github.ambry.network.http2.MultiplexedChannelRecordTest) Test(org.junit.Test)

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