Java Introduction to Building a Simple Netty Development Environment
- 2021-10-11 18:47:34
- OfStack
The following is the jar package for preparing Netty. If you know maven, it is naturally most convenient to use maven. Just import the following lines in the pom file
<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.16.Final</version>
</dependency>
Of course, don't worry if you don't know maven. You can download jar package directly in official website and click Jump. And in the editor to download the jar package into your lib, you can happily start Netty development
A simple netty case is posted below
1. Server-side code
1. EchoServerHandler.java
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter{
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// Converts the incoming message from the client to Netty Adj. ByteBuf Type
ByteBuf in = (ByteBuf) msg;
// Print incoming messages on the console
System.out.println(
"Server received: " + in.toString(CharsetUtil.UTF_8)
);
// Write the received message to the sender without flushing the outbound message
ctx.write(in);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// Flushes the unexecuted message to the remote node, And close the Channel
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
.addListener(ChannelFutureListener.CLOSE);
}
/**
* Exception handling
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// Print Exception Stack Trace
cause.printStackTrace();
// Close the Channel
ctx.close();
}
}
2. EchoServer.java
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 java.net.InetSocketAddress;
public class EchoServer {
private final static int port = 8080;
public static void main(String[] args) {
start();
}
private static void start() {
final EchoServerHandler serverHandler = new EchoServerHandler();
// Create EventLoopGroup
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
// Create EventLoopGroup
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
// Specifies the NIO Transmission Channel
.channel(NioServerSocketChannel.class)
// Sets the socket address using the specified port
.localAddress(new InetSocketAddress(port))
// Add 1 A EchoServerHandler To Channle Adj. ChannelPipeline
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//EchoServerHandler Be marked as @shareable, So we can always use the same case
socketChannel.pipeline().addLast(serverHandler);
}
});
try {
// Bind the server asynchronously ; Call sync Method blocks and waits until the binding completes
ChannelFuture f = b.bind().sync();
// Get Channel Adj. CloseFuture And blocks the current thread until it completes
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// Elegant closure EventLoopGroup Release all resources
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
2. Client code
1. EchoClientHandler.java
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
@Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// When notified Channel Is active when sending 1 Message
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
System.out.println(
"Client received: " + byteBuf.toString(CharsetUtil.UTF_8)
);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
2. EchoClient.java
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 java.net.InetSocketAddress;
public class EchoClient {
private final static String HOST = "localhost";
private final static int PORT = 8080;
public static void start() {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(HOST, PORT))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new EchoClientHandler());
}
});
try {
ChannelFuture f = bootstrap.connect().sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) {
start();
}
}
Run EchoServer. java and EchoClient. java. If the console prints separately
Server received: Netty rocks!
And
Client received: Netty rocks!
So congratulations, you can start the development of netty.
Click to view Netty combined with Protobuf codec