Search in sources :

Example 11 with LengthFieldBasedFrameDecoder

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);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) ResourcePatternResolver(org.springframework.core.io.support.ResourcePatternResolver) PrivateKey(java.security.PrivateKey) Resource(org.springframework.core.io.Resource) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 12 with LengthFieldBasedFrameDecoder

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();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) SocketChannel(io.netty.channel.socket.SocketChannel) StringDecoder(io.netty.handler.codec.string.StringDecoder) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) ChannelPipeline(io.netty.channel.ChannelPipeline) 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) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 13 with LengthFieldBasedFrameDecoder

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();
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) StringDecoder(io.netty.handler.codec.string.StringDecoder) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) IOException(java.io.IOException) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) StringEncoder(io.netty.handler.codec.string.StringEncoder) Bootstrap(io.netty.bootstrap.Bootstrap) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 14 with LengthFieldBasedFrameDecoder

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));
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) Bootstrap(io.netty.bootstrap.Bootstrap) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 15 with LengthFieldBasedFrameDecoder

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);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) MultithreadEventLoopGroup(io.netty.channel.MultithreadEventLoopGroup) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) SslContext(io.netty.handler.ssl.SslContext) LocalAddress(io.netty.channel.local.LocalAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) IOException(java.io.IOException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler)

Aggregations

LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)68 SocketChannel (io.netty.channel.socket.SocketChannel)35 LengthFieldPrepender (io.netty.handler.codec.LengthFieldPrepender)35 ChannelPipeline (io.netty.channel.ChannelPipeline)30 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)25 Bootstrap (io.netty.bootstrap.Bootstrap)19 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)19 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)19 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)18 ChannelFuture (io.netty.channel.ChannelFuture)14 EventLoopGroup (io.netty.channel.EventLoopGroup)14 Channel (io.netty.channel.Channel)13 StringEncoder (io.netty.handler.codec.string.StringEncoder)13 StringDecoder (io.netty.handler.codec.string.StringDecoder)12 SslContext (io.netty.handler.ssl.SslContext)12 EpollEventLoopGroup (io.netty.channel.epoll.EpollEventLoopGroup)9 CommandDecoder (io.pravega.shared.protocol.netty.CommandDecoder)8 CommandEncoder (io.pravega.shared.protocol.netty.CommandEncoder)8 IOException (java.io.IOException)8 ExceptionLoggingHandler (io.pravega.shared.protocol.netty.ExceptionLoggingHandler)7