Netty learning one: the first netty program

Posted by signs on Wed, 01 Jan 2020 06:19:25 +0100

Recently, after studying netty and reading the blog for a few days, I plan to write a hands-on program by myself.

This program is very simple: the client sends a ping, and the server will reply a pong accordingly. When the server loses the connection, it will be disconnected.

The whole code is divided into two parts: client and server. The structure is as follows:

Import netty package:

<dependency>
	<groupId>io.netty</groupId>
	<artifactId>netty-all</artifactId>
	<version>4.1.15.Final</version>
</dependency>

client terminal:

PingClient.java

package org.attempt.netty4.demo001.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class PingClient {

    /** Server IP address */
    private String host = "127.0.0.1";

    /** Server port */
    private int port = 8000;

    private EventLoopGroup group = null;
    private Bootstrap b = null;
    private Channel channel = null;

    public PingClient() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        b = new Bootstrap();
        b.group(group)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline()
                                //String decoding and encoding
                                .addLast(new StringDecoder())
                                .addLast(new StringEncoder())
                                //Client logic
                                .addLast(new PingClientHandler());
                    }
                });
    }

    public Channel getChannel() throws Exception {
        if(null == channel || !channel.isActive()) {
            channel = b.connect(host, port).sync().channel();
        }
        return channel;
    }

    public static void main(String[] args) throws Exception {
        PingClient client = null;
        try {
            client = new PingClient();
            Channel channel = client.getChannel();

            while(true) {
                //The status of the output channel, corresponding to close()
                System.out.println(channel.isOpen());
                //Judge connection status
                if(channel.isActive()) {
                    channel.writeAndFlush("ping");
                } else {
                    System.out.println("Lose connection, close client");
                    channel.close();
                    break;
                }
                Thread.sleep(5000);
            }
        } finally {
            if(null != client) {
                client.stop();
            }
        }
    }

    public void stop() {
        if(null != group) {
            //Exit gracefully and release resources of thread pool
            group.shutdownGracefully();
        }
    }

}

PingClientHandler.java

package org.attempt.netty4.demo001.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class PingClientHandler extends SimpleChannelInboundHandler {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("receive from server: " + msg.toString());
    }

}

server terminal: PongServer.java

package org.attempt.netty4.demo001.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class PongServer {

    public static void main(String[] args) throws Exception {
        int port = 8000;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                //Use default
            }
        }
        new PongServer().bind(port);
    }

    public void bind(int port) throws Exception {
        //Configure NIO thread group of server
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline()
                            //String decoding and encoding
                            .addLast(new StringDecoder())
                            .addLast(new StringEncoder())
                            //The logic of the server
                            .addLast(new PongServerHandler());
                        }
                    });

            //Binding port, synchronization waiting for success
            ChannelFuture f = b.bind(port).sync();

            //Wait for the server listening port to close
            f.channel().closeFuture().sync();
        } finally {
            //Exit gracefully and release resources of thread pool
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}

PongServerHandler.java

package org.attempt.netty4.demo001.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author admin
 * @date 2018-09-06 22:48
 */
public class PongServerHandler extends SimpleChannelInboundHandler {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("receive from client: " + msg.toString());
        //Return client message
        if(msg.toString().equals("ping")) {
            ctx.writeAndFlush("pong");
        } else {
            ctx.writeAndFlush("UNKONWN");
        }
    }

}

To run, start the server and then the client. The result is as follows:

  • server terminal:
receive from client: ping
receive from client: ping
receive from client: ping
receive from client: ping
receive from client: ping

Process finished with exit code -1
  • client terminal:
true
receive from server: pong
true
receive from server: pong
true
receive from server: pong
true
receive from server: pong
true
receive from server: pong
false
//Lose connection, close client

Some classes and usage in the code will be discussed later.

Topics: Netty Java socket codec