Netty4实例入门
建立两个maven模块Server和Client
maven项目导入
- 注意这里要配置configuration,不然后面执行mvn exec:java会出错
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.0.38.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2</version>
<configuration>
<mainClass>client.EchoClient</mainClass>
</configuration>
</plugin>
</plugins>
</build>
client模块下新建两个文件
EchoClient
public class EchoClient {
private final String host;
private final int port;
public EchoClient(String host,int port) {
this.host = host;
this.port = port;
}
public static void main(String[] args)
throws Exception {
String host = "127.0.0.1";
int port = 60296;
new EchoClient(host,port).start();
}
public void start() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap(); //1
b.group(group) //2
.channel(NioSocketChannel.class) //3
.remoteAddress(new InetSocketAddress(host, port)) //4
.handler(new ChannelInitializer<SocketChannel>() { //5
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast(
new EchoClientHandler());
}
});
ChannelFuture f = b.connect().sync(); //6
f.channel().closeFuture().sync(); //7
} finally {
group.shutdownGracefully().sync(); //8
}
}
}
EchoClientHandler
@ChannelHandler.Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel Active!");
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty Worked", CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
System.out.println("Client Received:"+ ByteBufUtil.hexDump(byteBuf.readBytes(byteBuf.readableBytes())));
}
}
在Server模块下新建两个文件
EchoServer
public class EchoServer {
private final int port;
public EchoServer(int port) {
this.port = port;
}
public static void main(String[] args)
throws Exception {
// 服务器监听端口号
int port = 60296;
new EchoServer(port).start();
}
public void start() throws Exception {
// NioEventLoopGroup是处理I/O操作的多线程事件循环
NioEventLoopGroup group = new NioEventLoopGroup();
try {
// ServerBootstrap是一个用于设置服务器的引导类。
ServerBootstrap b = new ServerBootstrap();
b.group(group)
.channel(NioServerSocketChannel.class) // 使用NioServerSocketChannel类,用于实例化新的通道以接受传入连接
.localAddress(new InetSocketAddress(port)) // 设置服务器监听端口号
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoServerHandler()); // 添加请求处理
}
});
// 绑定到端口和启动服务器
ChannelFuture f = b.bind().sync();
System.out.println(EchoServer.class.getName() +
" started and listening for connections on " + f.channel().localAddress());
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
}
}
EchoSereverHandler
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 覆盖channelRead()事件处理程序方法
System.out.println("Server channelRead!");
ByteBuf in = (ByteBuf) msg;
System.out.println(
"Server received: " + in.toString(CharsetUtil.UTF_8));
ctx.write(in);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx)
throws Exception {
// channelRead()执行完成后,关闭channel连接
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
.addListener(ChannelFutureListener.CLOSE);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
控制台执行
- 在项目的根目录下执行mvn clean package
- 在Server模块目录下执行 mvn exec:java
- 在Client模块目录下执行 mvn exec:java
执行结果如下图所示: