Search in sources :

Example 26 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project cradle by BingLau7.

the class EchoClient method start.

void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        // 指定 EventLoopGroup 以处理客户端时间;需要适用于 NIO 的实现
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host, port)).handler(new ChannelInitializer<SocketChannel>() {

            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new EchoClientHandler());
            }
        });
        // 连接远程节点,阻塞等待直到连接完成
        ChannelFuture f = b.connect().sync();
        // 阻塞,直到 Channel 关闭
        f.channel().closeFuture().sync();
    } finally {
        // 关闭线程池并释放所有的资源
        group.shutdownGracefully().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) InetSocketAddress(java.net.InetSocketAddress) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 27 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project cradle by BingLau7.

the class EchoServer method start.

void start() throws Exception {
    // 创建 Event-LoopGroup
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        // 创建 Server-Bootstrap
        ServerBootstrap b = new ServerBootstrap();
        b.group(group).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port)).childHandler(new ChannelInitializer<SocketChannel>() {

            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new EchoServerHandler());
            }
        });
        // 异步地绑定服务器;调用 sync() 方法阻塞等待直到绑定完成
        ChannelFuture f = b.bind().sync();
        System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());
        // 获取 Channel 的 CloseFuture,并且阻塞当前线程直到它完成
        f.channel().closeFuture().sync();
    } finally {
        // 关闭 EventLoopGroup,释放所有的资源
        group.shutdownGracefully().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 28 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project cradle by BingLau7.

the class NettyNioServer method server.

public void server(int port) throws Exception {
    final ByteBuf buf = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Hi!\r\n", Charset.forName("UTF-8")));
    // 为非阻塞模式使用 NioEventLoopGroup
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        // 创建 ServerBootstrap
        ServerBootstrap b = new ServerBootstrap();
        b.group(group).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port)).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                // 添加一个 ChannelInBoundHandlerAdapter 以拦截和处理事件
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        // 将消息写到客户端,并添加 ChannelFutureListener 以便消息已被写完就关闭连接
                        ctx.writeAndFlush(buf.duplicate()).addListener(ChannelFutureListener.CLOSE);
                    }
                });
            }
        });
        // 绑定服务器以接收连接
        ChannelFuture f = b.bind().sync();
        f.channel().closeFuture().sync();
    } finally {
        // 释放所有资源
        group.shutdownGracefully().sync();
    }
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) ByteBuf(io.netty.buffer.ByteBuf) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 29 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project aerospike-client-java by aerospike.

the class NettyCommand method executeCommand.

private void executeCommand() {
    try {
        Node node = command.getNode(cluster);
        conn = (NettyConnection) node.getAsyncConnection(eventState.index, null);
        if (conn != null) {
            InboundHandler handler = (InboundHandler) conn.channel.pipeline().last();
            handler.command = this;
            writeCommand();
            return;
        }
        try {
            final InboundHandler handler = new InboundHandler();
            handler.command = this;
            Bootstrap b = new Bootstrap();
            b.group(eventLoop.eventLoop);
            if (eventLoop.parent.isEpoll) {
                b.channel(EpollSocketChannel.class);
            } else {
                b.channel(NioSocketChannel.class);
            }
            b.option(ChannelOption.TCP_NODELAY, true);
            b.option(ChannelOption.AUTO_READ, false);
            b.handler(new ChannelInitializer<SocketChannel>() {

                @Override
                public void initChannel(SocketChannel ch) {
                    conn = new NettyConnection(ch, cluster.maxSocketIdleNanos);
                    ChannelPipeline p = ch.pipeline();
                    if (eventLoop.parent.sslContext != null) {
                        //InetSocketAddress address = node.getAddress();
                        //p.addLast(eventLoop.parent.sslContext.newHandler(ch.alloc(), address.getHostString(), address.getPort()));
                        p.addLast(eventLoop.parent.sslContext.newHandler(ch.alloc()));
                    }
                    p.addLast(handler);
                }
            });
            b.connect(node.getAddress());
        } catch (Exception e) {
            node.decrAsyncConnection(eventState.index);
            throw e;
        }
        eventState.errors = 0;
    } catch (AerospikeException.Connection ac) {
        eventState.errors++;
        onNetworkError(ac);
    } catch (Exception e) {
        // Fail without retry on unknown errors.
        eventState.errors++;
        fail();
        notifyFailure(new AerospikeException(e));
    }
}
Also used : AerospikeException(com.aerospike.client.AerospikeException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Node(com.aerospike.client.cluster.Node) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) AerospikeException(com.aerospike.client.AerospikeException) IOException(java.io.IOException)

Example 30 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project carbondata by apache.

the class DictionaryClient method startClient.

/**
   * start dictionary client
   *
   * @param address
   * @param port
   */
public void startClient(String address, int port) {
    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("DictionaryClientHandler", dictionaryClientHandler);
        }
    });
    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)

Aggregations

SocketChannel (io.netty.channel.socket.SocketChannel)65 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)34 ChannelPipeline (io.netty.channel.ChannelPipeline)31 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)28 Bootstrap (io.netty.bootstrap.Bootstrap)27 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)26 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)24 ChannelFuture (io.netty.channel.ChannelFuture)22 EventLoopGroup (io.netty.channel.EventLoopGroup)21 Channel (io.netty.channel.Channel)17 SslContext (io.netty.handler.ssl.SslContext)15 IOException (java.io.IOException)14 InetSocketAddress (java.net.InetSocketAddress)14 LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)9 LoggingHandler (io.netty.handler.logging.LoggingHandler)8 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)7 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)7 ByteBuf (io.netty.buffer.ByteBuf)6 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)6 ChannelInitializer (io.netty.channel.ChannelInitializer)6