Search in sources :

Example 16 with SocketChannel

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

the class EchoClient method main.

public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                }
                //p.addLast(new LoggingHandler(LogLevel.INFO));
                p.addLast(new EchoClientHandler());
            }
        });
        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}
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) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelPipeline(io.netty.channel.ChannelPipeline) SslContext(io.netty.handler.ssl.SslContext)

Example 17 with SocketChannel

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

the class EchoServer method main.

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.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 {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc()));
                }
                //p.addLast(new LoggingHandler(LogLevel.INFO));
                p.addLast(new EchoServerHandler());
            }
        });
        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();
        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 18 with SocketChannel

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

the class AbstractEventLoopTest method testReregister.

/**
     * Test for https://github.com/netty/netty/issues/803
     */
@Test
public void testReregister() {
    EventLoopGroup group = newEventLoopGroup();
    EventLoopGroup group2 = newEventLoopGroup();
    final EventExecutorGroup eventExecutorGroup = new DefaultEventExecutorGroup(2);
    ServerBootstrap bootstrap = new ServerBootstrap();
    ChannelFuture future = bootstrap.channel(newChannel()).group(group).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
        }
    }).handler(new ChannelInitializer<ServerSocketChannel>() {

        @Override
        public void initChannel(ServerSocketChannel ch) throws Exception {
            ch.pipeline().addLast(new TestChannelHandler());
            ch.pipeline().addLast(eventExecutorGroup, new TestChannelHandler2());
        }
    }).bind(0).awaitUninterruptibly();
    EventExecutor executor = future.channel().pipeline().context(TestChannelHandler2.class).executor();
    EventExecutor executor1 = future.channel().pipeline().context(TestChannelHandler.class).executor();
    future.channel().deregister().awaitUninterruptibly();
    Channel channel = group2.register(future.channel()).awaitUninterruptibly().channel();
    EventExecutor executorNew = channel.pipeline().context(TestChannelHandler.class).executor();
    assertNotSame(executor1, executorNew);
    assertSame(executor, future.channel().pipeline().context(TestChannelHandler2.class).executor());
}
Also used : DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) EventExecutorGroup(io.netty.util.concurrent.EventExecutorGroup) ServerSocketChannel(io.netty.channel.socket.ServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) ServerSocketChannel(io.netty.channel.socket.ServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) EventExecutor(io.netty.util.concurrent.EventExecutor) ServerSocketChannel(io.netty.channel.socket.ServerSocketChannel) Test(org.junit.Test)

Example 19 with SocketChannel

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

the class SocketSpdyEchoTest method testSpdyEcho.

private static void testSpdyEcho(ServerBootstrap sb, Bootstrap cb, final SpdyVersion version, boolean autoRead) throws Throwable {
    ByteBuf frames;
    switch(version) {
        case SPDY_3_1:
            frames = createFrames(3);
            break;
        default:
            throw new IllegalArgumentException("unknown version");
    }
    sb.childOption(ChannelOption.AUTO_READ, autoRead);
    cb.option(ChannelOption.AUTO_READ, autoRead);
    final SpdyEchoTestServerHandler sh = new SpdyEchoTestServerHandler(autoRead);
    final SpdyEchoTestClientHandler ch = new SpdyEchoTestClientHandler(frames.copy(), autoRead);
    sb.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel channel) throws Exception {
            channel.pipeline().addLast(new SpdyFrameCodec(version), sh);
        }
    });
    cb.handler(ch);
    Channel sc = sb.localAddress(0).bind().sync().channel();
    int port = ((InetSocketAddress) sc.localAddress()).getPort();
    Channel cc = cb.remoteAddress(NetUtil.LOCALHOST, port).connect().sync().channel();
    cc.writeAndFlush(frames);
    while (ch.counter < frames.writerIndex() - ignoredBytes) {
        if (sh.exception.get() != null) {
            break;
        }
        if (ch.exception.get() != null) {
            break;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        // Ignore.
        }
    }
    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
        throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
        throw ch.exception.get();
    }
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) SpdyFrameCodec(io.netty.handler.codec.spdy.SpdyFrameCodec) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) SocketChannel(io.netty.channel.socket.SocketChannel) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf) IOException(java.io.IOException)

Example 20 with SocketChannel

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

the class HttpClientCodecTest method testServerCloseSocketInputProvidesData.

@Test
public void testServerCloseSocketInputProvidesData() throws InterruptedException {
    ServerBootstrap sb = new ServerBootstrap();
    Bootstrap cb = new Bootstrap();
    final CountDownLatch serverChannelLatch = new CountDownLatch(1);
    final CountDownLatch responseRecievedLatch = new CountDownLatch(1);
    try {
        sb.group(new NioEventLoopGroup(2));
        sb.channel(NioServerSocketChannel.class);
        sb.childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                // Don't use the HttpServerCodec, because we don't want to have content-length or anything added.
                ch.pipeline().addLast(new HttpRequestDecoder(4096, 8192, 8192, true));
                ch.pipeline().addLast(new HttpObjectAggregator(4096));
                ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpRequest>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) {
                        // This is just a simple demo...don't block in IO
                        assertTrue(ctx.channel() instanceof SocketChannel);
                        final SocketChannel sChannel = (SocketChannel) ctx.channel();
                        /**
                             * The point of this test is to not add any content-length or content-encoding headers
                             * and the client should still handle this.
                             * See <a href="https://tools.ietf.org/html/rfc7230#section-3.3.3">RFC 7230, 3.3.3</a>.
                             */
                        sChannel.writeAndFlush(Unpooled.wrappedBuffer(("HTTP/1.0 200 OK\r\n" + "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n" + "Content-Type: text/html\r\n\r\n").getBytes(CharsetUtil.ISO_8859_1))).addListener(new ChannelFutureListener() {

                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                assertTrue(future.isSuccess());
                                sChannel.writeAndFlush(Unpooled.wrappedBuffer("<html><body>hello half closed!</body></html>\r\n".getBytes(CharsetUtil.ISO_8859_1))).addListener(new ChannelFutureListener() {

                                    @Override
                                    public void operationComplete(ChannelFuture future) throws Exception {
                                        assertTrue(future.isSuccess());
                                        sChannel.shutdownOutput();
                                    }
                                });
                            }
                        });
                    }
                });
                serverChannelLatch.countDown();
            }
        });
        cb.group(new NioEventLoopGroup(1));
        cb.channel(NioSocketChannel.class);
        cb.option(ChannelOption.ALLOW_HALF_CLOSURE, true);
        cb.handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(new HttpClientCodec(4096, 8192, 8192, true, true));
                ch.pipeline().addLast(new HttpObjectAggregator(4096));
                ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpResponse>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) {
                        responseRecievedLatch.countDown();
                    }
                });
            }
        });
        Channel serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
        int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();
        ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
        assertTrue(ccf.awaitUninterruptibly().isSuccess());
        Channel clientChannel = ccf.channel();
        assertTrue(serverChannelLatch.await(5, SECONDS));
        clientChannel.writeAndFlush(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"));
        assertTrue(responseRecievedLatch.await(5, SECONDS));
    } finally {
        sb.config().group().shutdownGracefully();
        sb.config().childGroup().shutdownGracefully();
        cb.config().group().shutdownGracefully();
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) 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) InetSocketAddress(java.net.InetSocketAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) PrematureChannelClosureException(io.netty.handler.codec.PrematureChannelClosureException) CodecException(io.netty.handler.codec.CodecException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.Test)

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