回声系统(客户端发什么服务器响应什么)
服务端代码
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class HelloServer {
public static void main(String[] args) {
// 创建启动器
new ServerBootstrap()
// 创建EventLoop事件监听处理组
.group(new NioEventLoopGroup())
// 设置ServerSocketChannel的实现NioServerSocketChannel
.channel(NioServerSocketChannel.class)
// 设置处理器
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
// 自定义处理器
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
// 监听读时间
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 打印上一步转换好的字符串
log.debug("服务器打印---{}", msg.toString());
// 创建buf对象
ByteBuf buffer = ctx.alloc().buffer(200);
// 往客户端回应
ctx.channel().writeAndFlush(buffer.writeBytes(msg.toString().getBytes()));
}
});
}
}).bind(8080); // 绑定的监听端口
}
}
客户端代码
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Scanner;
@Slf4j
public class HelloClient {
public static void main(String[] args) throws InterruptedException {
NioEventLoopGroup group = new NioEventLoopGroup();
//1 启动类
Channel channel = new Bootstrap()
// 2.添加EventLoop
.group(group)
// 3.选择客服端channel实现
.channel(NioSocketChannel.class)
// 4 添加处理器
.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringEncoder());
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf) msg;
log.debug("服务器返回---{}", byteBuf.toString(Charset.defaultCharset()));
// 释放buf对象
byteBuf.release();
}
});
}
// 连接地址
}).connect(new InetSocketAddress("127.0.0.1", 8080))
.sync()
.channel();
Scanner sc = new Scanner(System.in);
while (true) {
String name = sc.nextLine();
if (name.equals("q")) {
// 如果输入的是q 关闭服务器
channel.close();
log.debug("关闭服务器...");
break;
}
// 发送输入的字符串
channel.writeAndFlush(name);
}
ChannelFuture channelFuture = channel.closeFuture();
// 等待异步的关闭结束
channelFuture.sync();
// 关闭任务组对象
group.shutdownGracefully();
}
}
测试通过 ,正常关闭