use of io.netty.handler.codec.LengthFieldBasedFrameDecoder in project web3sdk by FISCO-BCOS.
the class ChannelConnections method startListen.
public void startListen(Integer port) {
if (running) {
logger.debug("服务已启动");
return;
}
logger.debug("初始化connections listen");
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
final ChannelConnections selfService = this;
final ThreadPoolTaskExecutor selfThreadPool = threadPool;
try {
serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource keystoreResource = resolver.getResource(getClientKeystorePath());
Resource caResource = resolver.getResource(getCaCertPath());
ks.load(keystoreResource.getInputStream(), getKeystorePassWord().toCharArray());
/*
* 每次连接使用新的handler
* 连接信息从socketChannel中获取
*/
ChannelHandler handler = new ChannelHandler();
handler.setConnections(selfService);
handler.setIsServer(true);
handler.setThreadPool(selfThreadPool);
SslContext sslCtx = SslContextBuilder.forServer((PrivateKey) ks.getKey("client", getClientCertPassWord().toCharArray()), (X509Certificate) ks.getCertificate("client")).trustManager(caResource.getFile()).build();
ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new LengthFieldBasedFrameDecoder(1024 * 1024 * 4, 0, 4, -4, 0), new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS), handler);
}
});
ChannelFuture future = serverBootstrap.bind(port);
future.get();
running = true;
} catch (Exception e) {
logger.error("系统错误", e);
}
}
use of io.netty.handler.codec.LengthFieldBasedFrameDecoder in project baseio by generallycloud.
the class NettyClientThread method main.
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group);
b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast("handler", new HelloClient());
}
});
System.out.println("################## Test start ####################");
ChannelFuture f = b.connect("127.0.0.1", 5656).sync();
System.out.println(f.isSuccess());
Channel channel = f.channel();
System.out.println("channel is active :" + channel.isActive() + ",channel:" + channel);
int len = 1024 * 64;
StringBuilder s = new StringBuilder(len);
for (int i = 0; i < len; i++) {
s.append(len % 10);
}
final String msg = s.toString();
ThreadUtil.execute(new Runnable() {
@Override
public void run() {
int i = 0;
for (; ; ) {
// String s = "hello Service! ---> :" + i;
ChannelFuture f = channel.writeAndFlush(msg);
ThreadUtil.sleep(1);
System.out.println(f.isDone() + "--------" + i);
i++;
}
}
});
ThreadUtil.sleep(Integer.MAX_VALUE);
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
use of io.netty.handler.codec.LengthFieldBasedFrameDecoder in project baseio by generallycloud.
the class TestLoadEchoClient1 method prepare.
@Override
public void prepare() throws Exception {
eventHandleAdaptor = new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// System.out.println("_________________"+msg);
// ctx.write(msg);
addCount(1);
}
};
Bootstrap b = new Bootstrap();
b.group(group);
b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, false);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast("handler", eventHandleAdaptor);
}
});
f = b.connect("localhost", 5656).sync();
}
use of io.netty.handler.codec.LengthFieldBasedFrameDecoder in project carbondata by apache.
the class NonSecureDictionaryClient method startClient.
/**
* start dictionary client
*
* @param address
* @param port
*/
@Override
public void startClient(String secretKey, String address, int port, boolean encryptSecureServer) {
LOGGER.audit("Starting client on " + address + " " + port);
long start = System.currentTimeMillis();
// Create an Event with 1 thread.
workerGroup = new NioEventLoopGroup(1);
Bootstrap clientBootstrap = new Bootstrap();
clientBootstrap.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// Based on length provided at header, it collects all packets
pipeline.addLast("LengthDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 2, 0, 2));
pipeline.addLast("NonSecureDictionaryClientHandler", nonSecureDictionaryClientHandler);
}
});
clientBootstrap.connect(new InetSocketAddress(address, port));
LOGGER.info("Dictionary client Started, Total time spent : " + (System.currentTimeMillis() - start));
}
use of io.netty.handler.codec.LengthFieldBasedFrameDecoder in project herddb by diennea.
the class NettyConnector method connect.
public static NettyChannel connect(String host, int port, boolean ssl, int connectTimeout, int socketTimeout, ChannelEventListener receiver, final ExecutorService callbackExecutor, final MultithreadEventLoopGroup networkGroup, final DefaultEventLoopGroup localEventsGroup) throws IOException {
try {
final SslContext sslCtx = !ssl ? null : SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
Class<? extends Channel> channelType;
InetSocketAddress inet = new InetSocketAddress(host, port);
SocketAddress address;
String hostAddress = NetworkUtils.getAddress(inet);
MultithreadEventLoopGroup group;
if (LocalServerRegistry.isLocalServer(hostAddress, port, ssl)) {
channelType = LocalChannel.class;
address = new LocalAddress(hostAddress + ":" + port + ":" + ssl);
group = localEventsGroup;
} else {
channelType = networkGroup instanceof EpollEventLoopGroup ? EpollSocketChannel.class : NioSocketChannel.class;
address = inet;
group = networkGroup;
}
Bootstrap b = new Bootstrap();
AtomicReference<NettyChannel> result = new AtomicReference<>();
b.group(group).channel(channelType).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout).handler(new ChannelInitializer<Channel>() {
@Override
public void initChannel(Channel ch) throws Exception {
NettyChannel channel = new NettyChannel(host + ":" + port, ch, callbackExecutor);
result.set(channel);
channel.setMessagesReceiver(receiver);
if (ssl) {
ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), host, port));
}
if (socketTimeout > 0) {
ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(socketTimeout));
}
ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
ch.pipeline().addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
//
ch.pipeline().addLast("messageencoder", new DataMessageEncoder());
ch.pipeline().addLast("messagedecoder", new DataMessageDecoder());
ch.pipeline().addLast(new InboundMessageHandler(channel));
}
});
LOGGER.log(Level.FINE, "connecting to {0}:{1} ssl={2} address={3}", new Object[] { host, port, ssl, address });
b.connect(address).sync();
return result.get();
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
Aggregations