
org.bdware.irp.irpclient.NettyIrpTCPClientChannel Maven / Gradle / Ivy
package org.bdware.irp.irpclient;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.irp.irplib.crypto.NettyTCPCodeC;
import org.bdware.irp.irplib.util.IrpCommon;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ThreadFactory;
public class NettyIrpTCPClientChannel extends NettyIrpClientChannel {
static Logger logger = LogManager.getLogger(NettyIrpTCPClientChannel.class);
final Bootstrap b = new Bootstrap();
static EventLoopGroup group = new NioEventLoopGroup(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
}
});
public NettyIrpTCPClientChannel() {
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
b.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.SO_REUSEADDR, true)
.option(ChannelOption.SO_LINGER, 0);
b.group(group);
handler = new NettyIrpClientHandler();
b.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(
new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new LengthFieldBasedFrameDecoder(IrpCommon.MAX_MESSAGE_PACKET_LENGTH, 16, 4, 0, 0))
.addLast(new NettyTCPCodeC())
.addLast(handler);
}
});
}
@Override
public void close() {
try {
channel.unsafe().closeForcibly();
} catch (Throwable e) {
}
if (handler != null) {
try {
handler.close();
} catch (Throwable e) {
}
}
isConnected = false;
try {
//group.shutdownGracefully();
} catch (Throwable e) {
}
}
@Override
public void connect(String targetUrl) throws URISyntaxException {
URI uri = new URI(targetUrl);
logger.debug("[URI Parse]scheme:" + uri.getScheme() + " host: " + uri.getHost() + " port: " + uri.getPort());
try {
channel = b.connect(uri.getHost(), uri.getPort()).sync().channel();
handler.setChannel(channel);
channel.config().setOption(ChannelOption.SO_LINGER, 0);
isConnected = true;
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
isConnected = false;
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy