All Downloads are FREE. Search and download functionalities are using the official Maven repository.

test.http.HttpNettyTestClient Maven / Gradle / Ivy

There is a newer version: 1.5.4
Show newest version
/*
 *    Copyright (c) [2021] [Peking University]
 *    [BDWare DOIP SDK] is licensed under Mulan PSL v2.
 *    You can use this software according to the terms and conditions of the Mulan PSL v2.
 *    You may obtain a copy of Mulan PSL v2 at:
 *             http://license.coscl.org.cn/MulanPSL2
 *    THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *    See the Mulan PSL v2 for more details.
 */

package test.http;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.URI;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class HttpNettyTestClient {
    static Logger LOGGER = LogManager.getLogger(HttpServerTest.class);

    public static void main(String[] args) throws Exception {
        // tcp://39.104.208.148:21042 1000 "bdware.test/small"
        if (args.length < 4) {
            System.out.println("Usage:\n tcp://39.104.208.148:21042 threadCount requestCount bdware.test/small largeorempty");
        }
        if (args.length >= 5 && args[4].startsWith("large")) {
            testClient(args[0], Integer.valueOf(args[1]), Integer.valueOf(args[2]), args[3], HttpServerTest.longStr);
            System.out.println("Request: Large, Response:" + args[3]);
        } else {
            testClient(args[0], Integer.valueOf(args[1]), Integer.valueOf(args[2]), args[3], "");
            System.out.println("Request: Small, Response:" + args[3]);
        }
        for (; ; ) ;
    }

    private static void testClient(String urlStr, Integer threadCount, Integer requestCount, String doid, String body) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
        AtomicInteger total = new AtomicInteger(0);
        AtomicInteger correct = new AtomicInteger(0);
        EventLoopGroup group = new NioEventLoopGroup();
        long start = System.currentTimeMillis();
        int maxFrameLength = 5 * 1024 * 1024;
        for (int i = 0; i < requestCount; i++)
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Bootstrap b = new Bootstrap();
                        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                                .option(ChannelOption.SO_KEEPALIVE, true)
                                .option(ChannelOption.SO_REUSEADDR, true)
                                .option(ChannelOption.SO_LINGER, 0);
                        b.option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                                new WriteBufferWaterMark(2 * maxFrameLength, 10 * maxFrameLength));
                        b.group(group);
                        final CountDownLatch countDownLatch = new CountDownLatch(1);
                        b.channel(NioSocketChannel.class)
                                .option(ChannelOption.TCP_NODELAY, true)
                                .handler(
                                        new ChannelInitializer() {
                                            @Override
                                            protected void initChannel(SocketChannel ch) {
                                                ChannelPipeline p = ch.pipeline();
                                                p.addLast(new HttpClientCodec())
                                                        .addLast(new SimpleChannelInboundHandler() {
                                                            @Override
                                                            protected void channelRead0(ChannelHandlerContext ctx, HttpResponse msg) throws Exception {
                                                                countDownLatch.countDown();
                                                                DefaultHttpResponse response = (DefaultHttpResponse) msg;
                                                                if (response.status().equals(HttpResponseStatus.OK)) {
                                                                    correct.incrementAndGet();
                                                                }
                                                            }
                                                        });
                                            }
                                        });
                        URI uri = new URI(urlStr);
                        Channel channel = b.connect(uri.getHost(), uri.getPort()).sync().channel();
                        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, urlStr, Unpooled.wrappedBuffer(body.getBytes()));
                        request.headers().add("doid", doid);
                        channel.writeAndFlush(request);
                        countDownLatch.await(5, TimeUnit.SECONDS);
                        channel.unsafe().closeForcibly();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        total.incrementAndGet();
                    }
                }
            });
        int circle = 0;
        for (; total.get() < requestCount; ) {
            if (++circle % 100 == 0)
                LOGGER.info(String.format("%d/%d --> total:%d", correct.get(), total.get(), requestCount));
            Thread.sleep(10);
        }
        int dur = (int) (System.currentTimeMillis() - start);
        LOGGER.info(String.format("%s Final Result:%d/%d dur:%d rps:%.2f ", urlStr, correct.get(), total.get(),
                dur, (correct.get() + 0.0D) * 1000.0D / (dur)));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy