Java Code Examples for io.netty.util.NetUtil#LOCALHOST

The following examples show how to use io.netty.util.NetUtil#LOCALHOST . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OioEventLoopTest.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Test
public void testTooManyAcceptedChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    assertThat(s.getInputStream().read(), is(-1));
    s.close();

    g.shutdownGracefully();
}
 
Example 2
Source File: OioEventLoopTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTooManyAcceptedChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    assertThat(s.getInputStream().read(), is(-1));
    s.close();

    g.shutdownGracefully();
}
 
Example 3
Source File: HttpServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ClientAndProtocolProvider.class)
void testHeadHeadersOnly(WebClient client, SessionProtocol protocol) throws Exception {
    assumeThat(protocol).isSameAs(H1C);

    final int port = server.httpPort();
    try (Socket s = new Socket(NetUtil.LOCALHOST, port)) {
        s.setSoTimeout(10000);
        final InputStream in = s.getInputStream();
        final OutputStream out = s.getOutputStream();
        out.write("HEAD /head-headers-only HTTP/1.0\r\n\r\n".getBytes(StandardCharsets.US_ASCII));

        // Should neither be chunked nor have content.
        assertThat(new String(ByteStreams.toByteArray(in)))
                .isEqualTo("HTTP/1.1 200 OK\r\n" +
                           "content-type: text/plain; charset=utf-8\r\n" +
                           "content-length: 6\r\n\r\n");
    }
}
 
Example 4
Source File: HttpServerPathTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void urlPathAssertion(HttpStatus expected, String path) throws Exception {
    final String requestString = "GET " + path + " HTTP/1.0\r\n\r\n";

    try (Socket s = new Socket(NetUtil.LOCALHOST, server.httpPort())) {
        s.setSoTimeout(10000);
        s.getOutputStream().write(requestString.getBytes(StandardCharsets.US_ASCII));
        assertThat(new String(ByteStreams.toByteArray(s.getInputStream()), StandardCharsets.US_ASCII))
                .as(path)
                .startsWith("HTTP/1.1 " + expected);
    }
}
 
Example 5
Source File: HealthCheckServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void assertResponseEquals(String request, String expectedResponse) throws Exception {
    final int port = server.httpPort();
    try (Socket s = new Socket(NetUtil.LOCALHOST, port)) {
        s.setSoTimeout(10000);
        final InputStream in = s.getInputStream();
        final OutputStream out = s.getOutputStream();
        out.write((request + "\r\n\r\n").getBytes(StandardCharsets.US_ASCII));

        // Should neither be chunked nor have content.
        assertThat(new String(ByteStreams.toByteArray(in), StandardCharsets.UTF_8))
                .isEqualTo(expectedResponse);
    }
}
 
Example 6
Source File: NioSocketChannelTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * Reproduces the issue #1679
 */
@Test
public void testFlushAfterGatheredFlush() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(NioServerSocketChannel.class);
        sb.childHandler(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                // Trigger a gathering write by writing two buffers.
                ctx.write(Unpooled.wrappedBuffer(new byte[] { 'a' }));
                ChannelFuture f = ctx.write(Unpooled.wrappedBuffer(new byte[] { 'b' }));
                f.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        // This message must be flushed
                        ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[]{'c'}));
                    }
                });
                ctx.flush();
            }
        });

        SocketAddress address = sb.bind(0).sync().channel().localAddress();

        Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) address).getPort());

        DataInput in = new DataInputStream(s.getInputStream());
        byte[] buf = new byte[3];
        in.readFully(buf);

        assertThat(new String(buf, CharsetUtil.US_ASCII), is("abc"));

        s.close();
    } finally {
        group.shutdownGracefully().sync();
    }
}
 
Example 7
Source File: AbstractSctpTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBootstrap serverBootstrap, Bootstrap bootstrap, ByteBufAllocator allocator) {
    addr = new InetSocketAddress(NetUtil.LOCALHOST, TestUtils.getFreePort());
    serverBootstrap.localAddress(addr);
    serverBootstrap.option(ChannelOption.ALLOCATOR, allocator);
    serverBootstrap.childOption(ChannelOption.ALLOCATOR, allocator);
    bootstrap.remoteAddress(addr);
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);
}
 
Example 8
Source File: EpollReuseAddrTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
private static Bootstrap createBootstrap() {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(EpollSocketTestPermutation.EPOLL_WORKER_GROUP);
    bootstrap.channel(EpollDatagramChannel.class);
    InetSocketAddress address = new InetSocketAddress(NetUtil.LOCALHOST, TestUtils.getFreePort());
    bootstrap.localAddress(address);
    return bootstrap;
}
 
Example 9
Source File: EpollReuseAddrTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static ServerBootstrap createServerBootstrap() {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(EpollSocketTestPermutation.EPOLL_BOSS_GROUP, EpollSocketTestPermutation.EPOLL_WORKER_GROUP);
    bootstrap.channel(EpollServerSocketChannel.class);
    bootstrap.childHandler(new DummyHandler());
    InetSocketAddress address = new InetSocketAddress(NetUtil.LOCALHOST, 0);
    bootstrap.localAddress(address);
    return bootstrap;
}
 
Example 10
Source File: NioSocketChannelTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Reproduces the issue #1679
 */
@Test
public void testFlushAfterGatheredFlush() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(NioServerSocketChannel.class);
        sb.childHandler(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                // Trigger a gathering write by writing two buffers.
                ctx.write(Unpooled.wrappedBuffer(new byte[] { 'a' }));
                ChannelFuture f = ctx.write(Unpooled.wrappedBuffer(new byte[] { 'b' }));
                f.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        // This message must be flushed
                        ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[]{'c'}));
                    }
                });
                ctx.flush();
            }
        });

        SocketAddress address = sb.bind(0).sync().channel().localAddress();

        Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) address).getPort());

        DataInput in = new DataInputStream(s.getInputStream());
        byte[] buf = new byte[3];
        in.readFully(buf);

        assertThat(new String(buf, CharsetUtil.US_ASCII), is("abc"));

        s.close();
    } finally {
        group.shutdownGracefully().sync();
    }
}
 
Example 11
Source File: HttpProxyHandlerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static void testInitialMessage(InetSocketAddress socketAddress, String hostPort,
                                       HttpHeaders headers) throws Exception  {
    InetSocketAddress proxyAddress = new InetSocketAddress(NetUtil.LOCALHOST, 8080);

    ChannelPromise promise = mock(ChannelPromise.class);
    verifyNoMoreInteractions(promise);

    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.connect(same(proxyAddress), isNull(InetSocketAddress.class), same(promise))).thenReturn(promise);

    HttpProxyHandler handler = new HttpProxyHandler(new InetSocketAddress(NetUtil.LOCALHOST, 8080), headers);
    handler.connect(ctx, socketAddress, null, promise);

    FullHttpRequest request = (FullHttpRequest) handler.newInitialMessage(ctx);
    try {
        assertEquals(HttpVersion.HTTP_1_1, request.protocolVersion());
        assertEquals(hostPort, request.uri());
        HttpHeaders actualHeaders = request.headers();
        assertEquals(hostPort, actualHeaders.get(HttpHeaderNames.HOST));

        if (headers != null) {
            // The actual request header is a strict superset of the custom header
            for (String name : headers.names()) {
                assertEquals(headers.getAll(name), actualHeaders.getAll(name));
            }
        }
    } finally {
        request.release();
    }
    verify(ctx).connect(proxyAddress, null, promise);
}
 
Example 12
Source File: UnmanagedTomcatServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void okWithoutAuthorityHeader() throws Exception {
    final int port = server.httpPort();
    try (Socket s = new Socket(NetUtil.LOCALHOST, port)) {
        final InputStream in = s.getInputStream();
        final OutputStream out = s.getOutputStream();
        out.write(("GET /some-webapp/ HTTP/1.1\r\n" +
                   "Content-Length: 0\r\n" +
                   "Connection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII));

        try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
            assertThat(br.readLine()).isEqualTo("HTTP/1.1 200 OK");
        }
    }
}
 
Example 13
Source File: HttpServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ClientAndProtocolProvider.class)
void testExpect100ContinueDoesNotBreakHttp1Decoder(WebClient client, SessionProtocol protocol)
        throws Exception {
    assumeThat(protocol).isSameAs(H1C);

    final int port = server.httpPort();
    try (Socket s = new Socket(NetUtil.LOCALHOST, port)) {
        s.setSoTimeout(10000);
        final InputStream in = s.getInputStream();
        final OutputStream out = s.getOutputStream();
        // Send 4 pipelined requests with 'Expect: 100-continue' header.
        out.write((Strings.repeat("POST /head-headers-only HTTP/1.1\r\n" +
                                  "Expect: 100-continue\r\n" +
                                  "Content-Length: 0\r\n\r\n", 3) +
                   "POST /head-headers-only HTTP/1.1\r\n" +
                   "Expect: 100-continue\r\n" +
                   "Content-Length: 0\r\n" +
                   "Connection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII));

        // '100 Continue' responses must appear once for each '200 OK' response.
        assertThat(new String(ByteStreams.toByteArray(in)))
                .isEqualTo(Strings.repeat("HTTP/1.1 100 Continue\r\n\r\n" +
                                          "HTTP/1.1 200 OK\r\n" +
                                          "content-type: text/plain; charset=utf-8\r\n" +
                                          "content-length: 6\r\n\r\n200 OK", 4));
    }
}
 
Example 14
Source File: UdpClientConnect.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
UdpClientConnect() {
	this.config = new UdpClientConfig(
			ConnectionProvider.newConnection(),
			Collections.singletonMap(ChannelOption.AUTO_READ, false),
			() -> new InetSocketAddress(NetUtil.LOCALHOST, DEFAULT_PORT));
}
 
Example 15
Source File: UdpServerBind.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
UdpServerBind() {
	this.config = new UdpServerConfig(
			Collections.singletonMap(ChannelOption.AUTO_READ, false),
			() -> new InetSocketAddress(NetUtil.LOCALHOST, DEFAULT_PORT));
}
 
Example 16
Source File: AbstractServerSocketTest.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
protected SocketAddress newSocketAddress() {
    return new InetSocketAddress(
            NetUtil.LOCALHOST, TestUtils.getFreePort());
}
 
Example 17
Source File: NioSocketChannelTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * Reproduces the issue #1600
 */
@Test
public void testFlushCloseReentrance() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    try {
        final Queue<ChannelFuture> futures = new LinkedBlockingQueue<ChannelFuture>();

        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(NioServerSocketChannel.class);
        sb.childOption(ChannelOption.SO_SNDBUF, 1024);
        sb.childHandler(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                // Write a large enough data so that it is split into two loops.
                futures.add(ctx.write(
                        ctx.alloc().buffer().writeZero(1048576)).addListener(ChannelFutureListener.CLOSE));
                futures.add(ctx.write(ctx.alloc().buffer().writeZero(1048576)));
                ctx.flush();
                futures.add(ctx.write(ctx.alloc().buffer().writeZero(1048576)));
                ctx.flush();
            }
        });

        SocketAddress address = sb.bind(0).sync().channel().localAddress();

        Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) address).getPort());

        InputStream in = s.getInputStream();
        byte[] buf = new byte[8192];
        for (;;) {
            if (in.read(buf) == -1) {
                break;
            }

            // Wait a little bit so that the write attempts are split into multiple flush attempts.
            Thread.sleep(10);
        }
        s.close();

        assertThat(futures.size(), is(3));
        ChannelFuture f1 = futures.poll();
        ChannelFuture f2 = futures.poll();
        ChannelFuture f3 = futures.poll();
        assertThat(f1.isSuccess(), is(true));
        assertThat(f2.isDone(), is(true));
        assertThat(f2.isSuccess(), is(false));
        assertThat(f2.cause(), is(instanceOf(ClosedChannelException.class)));
        assertThat(f3.isDone(), is(true));
        assertThat(f3.isSuccess(), is(false));
        assertThat(f3.cause(), is(instanceOf(ClosedChannelException.class)));
    } finally {
        group.shutdownGracefully().sync();
    }
}
 
Example 18
Source File: AbstractClientSocketTest.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
protected SocketAddress newSocketAddress() {
    return new InetSocketAddress(
            NetUtil.LOCALHOST, TestUtils.getFreePort());
}
 
Example 19
Source File: ProxyServer.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
public final InetSocketAddress address() {
    return new InetSocketAddress(NetUtil.LOCALHOST, ch.localAddress().getPort());
}
 
Example 20
Source File: NioSocketChannelTest.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
/**
 * Reproduces the issue #1600
 */
@Test
public void testFlushCloseReentrance() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    try {
        final Queue<ChannelFuture> futures = new LinkedBlockingQueue<ChannelFuture>();

        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(NioServerSocketChannel.class);
        sb.childOption(ChannelOption.SO_SNDBUF, 1024);
        sb.childHandler(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                // Write a large enough data so that it is split into two loops.
                futures.add(ctx.write(
                        ctx.alloc().buffer().writeZero(1048576)).addListener(ChannelFutureListener.CLOSE));
                futures.add(ctx.write(ctx.alloc().buffer().writeZero(1048576)));
                ctx.flush();
                futures.add(ctx.write(ctx.alloc().buffer().writeZero(1048576)));
                ctx.flush();
            }
        });

        SocketAddress address = sb.bind(0).sync().channel().localAddress();

        Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) address).getPort());

        InputStream in = s.getInputStream();
        byte[] buf = new byte[8192];
        for (;;) {
            if (in.read(buf) == -1) {
                break;
            }

            // Wait a little bit so that the write attempts are split into multiple flush attempts.
            Thread.sleep(10);
        }
        s.close();

        assertThat(futures.size(), is(3));
        ChannelFuture f1 = futures.poll();
        ChannelFuture f2 = futures.poll();
        ChannelFuture f3 = futures.poll();
        assertThat(f1.isSuccess(), is(true));
        assertThat(f2.isDone(), is(true));
        assertThat(f2.isSuccess(), is(false));
        assertThat(f2.cause(), is(instanceOf(ClosedChannelException.class)));
        assertThat(f3.isDone(), is(true));
        assertThat(f3.isSuccess(), is(false));
        assertThat(f3.cause(), is(instanceOf(ClosedChannelException.class)));
    } finally {
        group.shutdownGracefully().sync();
    }
}