- Netty Server
public class NettyServer {
public static void main(String[] args) throws InterruptedException {
//处理连接,任务分发
EventLoopGroup boosGroup = new NioEventLoopGroup(1);
// 工作线程池,默认cpu核数*2
EventLoopGroup workGroup = new NioEventLoopGroup();
try {
//服务端启动对象
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boosGroup, workGroup)
// 使用NioServerSocketChannel作为服务器的通道实现
.channel(NioServerSocketChannel.class)
// 初始化服务器端队列大小。
// 因为服务端处理客户端连接是按需执行的,所以同意时间只能处理一个客户端实现
// 多个客户端同时进行连接时,服务端将无法及时处理的客户端连接请求放在队列中等待处理
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// 添加handler,对于netty,大部分情况下都是在写各种handler
ch.pipeline().addLast(new NettyServerHandler());
}
});
System.out.println("Netty server start...");
// bind属于异步操作,sync是等待异步操作执行完毕
ChannelFuture channelFuture = bootstrap.bind(8090).sync();
// 给ChannelFuture注册监听器,监听我们关心的事件
channelFuture.addListener((ChannelFutureListener) channelFuture1 -> {
if (channelFuture1.isSuccess()) {
System.out.println("success monitor port 8090");
} else {
System.out.println("Failed monitor port 8090");
}
});
//监听通道关闭,closeFuture是异步操作
// sync同步等待关闭处理完毕
channelFuture.channel().closeFuture().sync();
} finally {
boosGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
- Netty Server Handler
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
/**
* 读取客户端数据
* @param ctx 含有通道Channel,管道Pipeline
* @param msg 客户端发送的数据
* @throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Server Thread:" + Thread.currentThread().getName());
ByteBuf buf = (ByteBuf) msg;
System.out.println("Receive message from client:" + buf.toString(CharsetUtil.UTF_8));
}
/**
* 数据读取完毕处理方法
* @param ctx
* @throws Exception
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ByteBuf buf = Unpooled.copiedBuffer("Hello Client.", CharsetUtil.UTF_8);
ctx.writeAndFlush(buf);
}
/**
* 处理异常
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
- Netty Client
public class NettyClient {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.group(group)
.channel(NioSocketChannel.class) // 服务端是NioServerSocketChannel
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new NettyClientHandler());
}
});
System.out.println("Netty client start");
// 启动客户端,连接服务端
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8090).sync();
channelFuture.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}
- Netty Client Handler
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
/**
* 客户端与服务端建立连接后,会出发此方法
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ByteBuf buf = Unpooled.copiedBuffer("Hello Server", CharsetUtil.UTF_8);
ctx.writeAndFlush(buf);
}
/**
* 收到服务端数据数据时,会触发此方法
* @param ctx
* @param msg
* @throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
System.out.println("receive message from server:" + buf.toString(CharsetUtil.UTF_8));
System.out.println("server address is:" + ctx.channel().remoteAddress());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
maven依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.35.Final</version>
</dependency>