客户端代码:
public class NettyClient {
public static void main(String[] args) {
NioEventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE,Delimiters.lineDelimiter()[0]));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new ClientHandler());
ch.pipeline().addLast(new StringEncoder());
}
});
ChannelFuture f = b.connect("localhost", 10007).sync();
String content = "张三\r\n";
ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer();
//将字节数组填充到buf中
buf.writeBytes(content.getBytes(Charset.defaultCharset()));
f.channel().writeAndFlush(buf);
f.channel().closeFuture().sync();
Object result = f.channel().attr(AttributeKey.valueOf("key")).get();
System.out.println(result);
}catch (Exception e) {
e.printStackTrace();
}finally {
group.shutdownGracefully();
}
}
}
服务端代码:
public class NettyServer {
public void start(){
//服务端开启2个group,一个用于监听事件(单线程),一个用于处理I/O
EventLoopGroup parent = new NioEventLoopGroup(1);
EventLoopGroup child = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(parent, child).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()[0]));
ch.pipeline().addLast(new NettyServerHandler());
ch.pipeline().addLast(new StringEncoder(Charset.defaultCharset()));
}
});
ChannelFuture future = b.bind(10007).sync();
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally {
parent.shutdownGracefully();
child.shutdownGracefully();
}
}
public static void main(String[] args) {
NettyServer n = new NettyServer();
n.start();
}
}
ClientHandler代码
public class ClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
super.channelRegistered(ctx);
System.out.println("--------------------------------------");
System.out.println("客户端管道注册完毕"+ctx.channel().toString());
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
System.out.println("客户端可用");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("客户端读取数据");
ctx.channel().attr(AttributeKey.valueOf("key")).set(msg);
ctx.channel().close();
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
super.channelUnregistered(ctx);
System.out.println("客户端管道注销");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelInactive(ctx);
System.out.println("客户端管道不可用");
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
super.channelReadComplete(ctx);
System.out.println("客户端管道读取数据完毕");
}
}
ServerHandler
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
super.channelRegistered(ctx);
System.out.println("管道注册完毕"+ctx.channel().toString());
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelUnregistered(ctx);
System.out.println("管道注销完毕");
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelActive(ctx);
System.out.println("管道变得可用");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
System.out.println("管道变得不可用");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("====================读取数据");
if(msg instanceof ByteBuf){
ByteBuf b = (ByteBuf)msg;
String content = b.toString(Charset.defaultCharset());
System.out.println(content);
String s = "李四\r\n";
ctx.channel().writeAndFlush(s);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("管道读数据完毕");
}
}