[JAVA] I tried to implement the client using Netty

at first

Last time I made a server using Netty, but today I will continue to implement it on the client side as well.

Implementation

➀ Processing such as access generation and termination


public class EchoClient {
    private final String host;
    private final int port;

    public EchoClient() {
        this(0);
    }

    public EchoClient(int port) {
        this("localhost", port);
    }

    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(this.host, this.port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            System.out.println("connected...");
                            ch.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            System.out.println("created..");

            ChannelFuture cf = b.connect().sync();
            System.out.println("connected...");

            cf.channel().closeFuture().sync();
            System.out.println("closed..");
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        new EchoClient("127.0.0.1", 31535).start();
    }
}

② Function activated by timing (should be callback)

--channelActive () --When a connection to the server is created --channelRead0 () --When the server receives the data --exceptionCaught () --When a reller is detected


public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("client channelActive..");
        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("client channelRead..");
        ByteBuf buf = msg.readBytes(msg.readableBytes());
        System.out.println("Client received:" + ByteBufUtil.hexDump(buf) + "; The value is:" + buf.toString(Charset.forName("utf-8")));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}

Result authentication

** Starting the server and waiting for a connection **

class EchoServer started and listen on /0:0:0:0:0:0:0:0:31535

** Start the server and make a request to the server ** ** The output of each client and server is as follows **

--Client

created..
connected...
client channelActive..
connected...
client channelRead..
Client received:4e6574747920726f636b7321; The value is:Netty rocks!
closed..

Process finished with exit code 0

--Server

class EchoServer started and listen on /0:0:0:0:0:0:0:0:31535
connected...; Client:/127.0.0.1:56967
server channelRead...; received:PooledUnsafeDirectByteBuf(ridx: 0, widx: 12, cap: 1024)
server channelReadComplete..

Summary

This time I tried to make a NIO transfer path using Netty, compared to ServerSocketChannel and SocketChannel, it became easier because there was no need to write a low-level API.

Recommended Posts

I tried to implement the client using Netty
I tried to implement a server using Netty
I tried to implement the Iterator pattern
I tried to implement Enigma
I tried to implement the Euclidean algorithm in Java
I tried to explain the method
I tried to build the environment little by little using docker
I tried to summarize the Stream API
I tried to implement the image preview function with Rails / jQuery
I tried to display the calendar on the Eclipse console using Java.
I tried to organize the session in Rails
How to implement the breadcrumb function using gretel
I tried using TestNG
I tried using Galasa
[API] I tried using the zip code search API
I tried to set tomcat to run the Servlet.
I tried using the profiler of IntelliJ IDEA
Rails API mode I tried to implement the keyword multiple search function using arrays and iterative processing.
[JDBC ③] I tried to input from the main method using placeholders and arguments.
I tried to operate SQS using AWS Java SDK
05. I tried to stub the source of Spring Boot
I want to judge the range using the monthly degree
I tried to reduce the capacity of Spring Boot
I tried using the Migration Toolkit for Application Binaries
I tried to implement Stalin sort with Java Collector
[Java] I tried to implement Yahoo API product search
I want to call the main method using reflection
I tried using Apache Wicket
I tried using Java REPL
I tried the FizzBuzz problem
I tried to verify yum-cron
[Rails] How to connect to an external API using HTTP Client (I tried connecting to Qiita API)
I tried to investigate the mechanism of Emscripten by using it with the Sudoku solver
I tried to summarize the basic grammar of Ruby briefly
[Rails] I tried to implement batch processing with Rake task
I tried using Dapr in Java to facilitate microservice development
I tried to implement a buggy web application in Kotlin
I tried to make a client of RESAS-API in Java
I tried to get started with Swagger using Spring Boot
I tried using the CameraX library with Android Java Fragment
I tried to touch the asset management application using the emulator of the distributed ledger Scalar DLT
I tried using JOOQ with Gradle
I tried to summarize iOS 14 support
I tried to interact with Java
I tried the Java framework "Quarkus"
[Rails] I tried deleting the application
The story I wanted to unzip
I tried using Java8 Stream API
[Java] Try to implement using generics
I tried using JWT in Java
I tried to summarize Java learning (1)
[Android] I tried using Coordinator Layout.
I tried using Pari gp container
I tried using WebAssembly Stadio (2018/4/17 version)
I tried to summarize Java 8 now
I tried to chew C # (polymorphism: polymorphism)
I tried using Java memo LocalDate
I tried to explain Active Hash
I tried using GoogleHttpClient of Java
I tried to sort the data in descending order, ascending order / Rails
I tried to integrate Docker and Maven / Netbean nicely using Jib