b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// 1.定义分隔符
ByteBuf delimiter = Unpooled.copiedBuffer(“$_”.getBytes());
// 2.添加分隔符解码器 单条消息最大长度1024,
// 当到达长度后仍然没有查找到分隔符,就抛TooLongFrameException
// 第二个参数是分隔符缓冲对象
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
// 3.添加字符串处理解码器
ch.pipeline().addLast(new StringDecoder());
// 4.添加自定义的处理器
ch.pipeline().addLast(new EchoServerHandler());
}
});
// 绑定端口,同步等待成功
ChannelFuture f = b.bind(port).sync();
// 等待服务端监听端口关闭
f.channel().closeFuture().sync();
} finally {
// 优雅退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
if(args!=null && args.length > 0){
try{
port = Integer.valueOf(args[0]);
}catch(NumberFormatException e){
// 采用默认值
}
}
new EchoServer().bind(port);
}
}
EchoServerHandler
package com.dpb.netty.demo3;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdap