分隔符和定长解码器的应用
DelimiterBasedFrameDecoder编解码器使用示例
服务端代码
package com.su.netty.server;
import com.su.netty.handler.EchoServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
* @ClassName:EchoServer
* @Author: sz
* @Date: 2022/9/16 9:33
* @Description:
*/
public class EchoServer {
public void bind(int port) throws InterruptedException {
//配置服务端的NIO线程组
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.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 socketChannel) throws Exception {
ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));
socketChannel.pipeline().addLast(new StringDecoder());
socketChannel.pipeline().addLast(new EchoServerHandler());
}
});
//绑定端口 同步等待成功
ChannelFuture future = serverBootstrap.bind(port).sync();
//等待服务器监听关闭
future.channel().closeFuture().sync();
}finally {
//优雅退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
int port = 8080;
if(args !=null && args.length>0){
try {
port = Integer.parseInt(args[0]);
}catch (Exception e){
}
}
new EchoServer().bind(port);
}
class EchoServerHandler extends ChannelInboundHandlerAdapter {
int counter = 0;
@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 byteBuf = Unpooled.copiedBuffer(body.getBytes());
ctx.writeAndFlush(byteBuf);
}
}
}
客户端代码
package com.su.netty.client;
import com.su.netty.handler.EchoClientHandler;
import com.su.netty.handler.EchoServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
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;
import java.net.InetSocketAddress;
/**
* @ClassName:EchoClient
* @Author: sz
* @Date: 2022/9/16 9:33
* @Description:
*/
public class EchoClient {
public void connect(int port,String host)throws Exception {
//配置NIO 客户端线程组
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY,true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));
socketChannel.pipeline().addLast(new StringDecoder());
socketChannel.pipeline().addLast(new EchoClientHandler());
}
});
//发起异步连接操作
ChannelFuture sync = bootstrap.connect(new InetSocketAddress(host,port)).sync();
//等待客户端连接关闭
sync.channel().closeFuture().sync();
}finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
if(args !=null && args.length>0){
try {
port = Integer.parseInt(args[0]);
}catch (Exception e){
}
}
new EchoClient().connect(port,"127.0.0.1");
}
class EchoClientHandler extends ChannelInboundHandlerAdapter {
private int counter;
static final String ECHO_REQ = "HI,Lilinfeng .Welcome to Netty.$_";
public EchoClientHandler(){}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
for (int i=0 ;i<10 ;i++){
ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes()));
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("This is "+ ++counter +"times receive server :[" + msg + "]");
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
}
}
执行结果
Server
九月 16, 2022 11:33:52 上午 io.netty.handler.logging.LoggingHandler channelRegistered
信息: [id: 0x0615a94f] REGISTERED
九月 16, 2022 11:33:52 上午 io.netty.handler.logging.LoggingHandler bind
信息: [id: 0x0615a94f] BIND: 0.0.0.0/0.0.0.0:8080
九月 16, 2022 11:33:52 上午 io.netty.handler.logging.LoggingHandler channelActive
信息: [id: 0x0615a94f, L:/0:0:0:0:0:0:0:0:8080] ACTIVE
九月 16, 2022 11:34:04 上午 io.netty.handler.logging.LoggingHandler channelRead
信息: [id: 0x0615a94f, L:/0:0:0:0:0:0:0:0:8080] READ: [id: 0x7b5bc0f1, L:/127.0.0.1:8080 - R:/127.0.0.1:50770]
九月 16, 2022 11:34:04 上午 io.netty.handler.logging.LoggingHandler channelReadComplete
信息: [id: 0x0615a94f, L:/0:0:0:0:0:0:0:0:8080] READ COMPLETE
This is 1 times receive client :[HI,Lilinfeng .Welcome to Netty.]
This is 2 times receive client :[HI,Lilinfeng .Welcome to Netty.]
This is 3 times receive client :[HI,Lilinfeng .Welcome to Netty.]
This is 4 times receive client :[HI,Lilinfeng .Welcome to Netty.]
This is 5 times receive client :[HI,Lilinfeng .Welcome to Netty.]
This is 6 times receive client :[HI,Lilinfeng .Welcome to Netty.]
This is 7 times receive client :[HI,Lilinfeng .Welcome to Netty.]
This is 8 times receive client :[HI,Lilinfeng .Welcome to Netty.]
This is 9 times receive client :[HI,Lilinfeng .Welcome to Netty.]
This is 10 times receive client :[HI,Lilinfeng .Welcome to Netty.]
Client
This is 1times receive server :[HI,Lilinfeng .Welcome to Netty.]
This is 2times receive server :[HI,Lilinfeng .Welcome to Netty.]
This is 3times receive server :[HI,Lilinfeng .Welcome to Netty.]
This is 4times receive server :[HI,Lilinfeng .Welcome to Netty.]
This is 5times receive server :[HI,Lilinfeng .Welcome to Netty.]
This is 6times receive server :[HI,Lilinfeng .Welcome to Netty.]
This is 7times receive server :[HI,Lilinfeng .Welcome to Netty.]
This is 8times receive server :[HI,Lilinfeng .Welcome to Netty.]
This is 9times receive server :[HI,Lilinfeng .Welcome to Netty.]
This is 10times receive server :[HI,Lilinfeng .Welcome to Netty.]