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();
}
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);
}
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);
}
}
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();
}
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();
}
}
Aggregations