Netty是一个提供异步事件驱动的网络应用开发框架(NIO框架)。
首先沾上我们的Manen依赖↓
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.25.Final</version>
</dependency>
如何建立服务器?如下↓
public void bind(int port){
//实例化两个线程组
//负责接受客户端的连接 因为它只负责接受客户端连接所以一般指定为1就行
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
//负责读写以及其他操作
NioEventLoopGroup workGroup = new NioEventLoopGroup();
//服务器的引导类,负责配置服务器的各种参数
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workGroup)//绑定两个线程组
.channel(NioServerSocketChannel.class)//设置NIO的模式
.childHandler(new MyInitializer()).bind(port); //子处理器
}
子处理器干代码↓
//channel注册后,会执行里面的相应的初始化方法
public class MyInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
// 通过SocketChannel去获得对应的管道
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast("MyDecoder",new MyDecoder());//自定义解码器 入栈
pipeline.addLast(new StringEncoder());//框架自带编码器 出栈
pipeline.addLast(new MyHandle2());//添加自定义处理器(读取客户端发送的数据,在此之前经过了前面解码器的解码)项目业务一般写在此处
}
}
自定义解码器↓
public class MyDecoder extends ByteToMessageDecoder {
// private final Queue<String> values = new LinkedList<>();
// private final ByteBuf tmpByteBuf = Unpooled.buffer(1024);
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf inBuf, List<Object> list) throws Exception {
int i = inBuf.readableBytes();
byte[] array = new byte[i];
inBuf.readBytes(array,0,i);
String s1 = new String(array, Charset.forName("UTF-8"));
list.add(s1);
}
}
自定义处理器读取客户端数据
public class MyHandle2 extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msgStr) throws Exception {
ctx.writeAndFlush(msgStr+" world!");
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel注册时调用");
super.channelRegistered(ctx);
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel移除时调用");
super.channelUnregistered(ctx);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel活跃时调用");
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel不活跃时调用");
super.channelInactive(ctx);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("channeld读取完毕时调用");
super.channelReadComplete(ctx);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
System.out.println("用户事件触发时调用");
super.userEventTriggered(ctx, evt);
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel可写更改时调用");
super.channelWritabilityChanged(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("捕获到异常时调用");
super.exceptionCaught(ctx, cause);
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("自定义处理器类添加时调用");
super.handlerAdded(ctx);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
System.out.println("自定义处理器类移除调用");
super.handlerRemoved(ctx);
}
}
客户端如何建立?↓
public void bind(String ip,int port){
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap .group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new StringEncoder());//编码器
ch.pipeline().addLast(new MyDecoder());//解码器
ch.pipeline().addLast(new MyHandle());//自定义处理器 一般项目的业务写在这里
}
});
//连接服务端
ChannelFuture future = bootstrap.connect(ip, port).sync();
//对通道关闭进行监听
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
总结:客户端和服务端的开发过程大致差不多,区别如下
1-两者的引导类不同服务端的引导类是ServerBootstrap,而客户端的引导类是Bootstrap
2-服务端的一般情况下最好使用两个EventLoopGroup,而客户端一个就行,因为客户端并不需要独立的线程去监听客户端连接,也不需要通过一个单独的客户端线程去连接服务端。