public void bind(int port) throws Exception {
// 配置服务端的NIO线程组
// 服务端接受客户端的连接
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
// 进行SocketChannel的网络读写
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@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.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
-
DelimiterBasedFrameDecoder 案例
-
自定义处理器
-
@author 波波烤鸭
*/
public class EchoServerHandler extends ChannelHandlerAdapter{
// 统计接收消息的数量
private int counter;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 获取客户端传递的消息
String body = (String) msg;
// 打印消息
System.out.println("This is "+ ++counter + " times receive client :["+body+"]");
// 分隔符已经被截取掉了,响应信息的时候我们需要再加上分隔符
body += "$_";
ByteBuf echo = Unpooled.copiedBuffer(body.getBytes());
ctx.writeAndFlush(echo);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close(); // 发生异常关闭链路
}
}
[](()客户断
EchoClient
package com.dpb.netty.demo3;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
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 io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
/**
-
DelimiterBasedFrameDecoder 案例 客户端
-
@author 波波烤鸭
*/
public class EchoClient {
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 EchoClient().connector(port, "127.0.0.1");
}
public void connector(int port, String host) throws Exception {
// 配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// TODO Auto-generated method stub
// 1.定义分隔符
ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
// 2.添加分隔符解码器
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
// 3.添加字符串处理解码器
ch.pipeline().addLast(new StringDecoder());
// 4.添加自定义的处理器
ch.pipeline().addLast(new EchoClientHandler());
}
});
// 发起异步连接操作
ChannelFuture f = b.connect(host, port).sync();
// 等待客户端链路关闭
f.channel().closeFuture().sync();
} finally {
// 优雅退出,释放NIO线程组
group.shutdownGracefully();
}
}
}
EchoClientHandler
package com.dpb.netty.demo3;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
-
DelimiterBasedFrameDecoder 案例
-
自定义客户端处理器
-
@author 波波烤鸭
*/
public class EchoClientHandler extends ChannelHandlerAdapter{
private int counter;
static final String ECHOREQ = "Hi , bobo烤鸭. Welcome to Netty.$";
public EchoClientHandler(){
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
// 发送消息别立马刷新
ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes()));
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// TODO Auto-generated method stub
System.out.println("This is "+ ++counter + "time recevice server :【"+msg+"】");
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
cause.printStackTrace();
ctx.close();
}
}
[](()测试
服务端运行结果
客户端运行结果
服务端成功接收到了客户端发送的10条信息,客户端成功接收到了服务端返回的10条信息,测试结果表明使用DelimiterBasedFrameDecoder可以自动对采用分隔符做码流结束标识的消息进行解码。运行多次的原因是模拟TCP粘包/拆包,如果没有DelimiterBasedFrameDecoder解码处理,服务端和客户端都将运行失败,如下:
输出结果:
This is 1 times receive client :
[Hi , bobo烤鸭. Welcome to Netty.$_Hi ,
bobo烤鸭. Welcome to Netty.$_Hi ,
bobo烤鸭. Welcome to Netty.$_Hi ,
bobo烤鸭. Welcome to Netty.$_Hi ,
bobo烤鸭. Welcome to Netty.$_Hi ,
bobo烤鸭. Welcome to Netty.$_Hi ,
bobo烤鸭. Welcome to Netty.$_Hi ,
bobo烤鸭. Welcome to Netty.$_Hi ,
bobo烤鸭. Welcome to Netty.$_Hi ,
bobo烤鸭. Welcome to Netty.$_]
客户端发送的10条信息,在服务端粘包成一条信息了。那么响应信息肯定也是一条了。
[](()FixedLengthFrameDecoder