服务器
public class HelloServer {
public static void main(String[] args) {
// 1 启动器负责组装netty组件,启动服务器
new ServerBootstrap()
// 2 group组 线程和选择器
.group(new NioEventLoopGroup())
// 选择实现 nio oio bio epoll
// 3 选择服务器的 ServerSocketChannel 实现
.channel(NioServerSocketChannel.class)
// 4 负责处理连接 负责处理读写 决定了worker能处理哪些操作
.childHandler(
// 代表和客户端进行数据读写的通道,负责添加别的handler
new ChannelInitializer() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
// 6 添加具体handler
ch.pipeline().addLast(new StringDecoder()); //将byteBuffer转换为字符串
ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){ // 自定义handler
// 读事件
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 打印上一步转换好的字符串
System.out.println(msg);
}
});
}
})
// 绑定监听端口
.bind(8888);
}
}
客户端
public class HelloClient {
public static void main(String[] args) throws InterruptedException {
// 启动类
new Bootstrap()
// 添加事件循环
.group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
// 初始化器,在连接建立后会调用
.handler(new ChannelInitializer() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringEncoder());
}
})
.connect(new InetSocketAddress("localhost",8888))
.sync()
.channel()
.writeAndFlush("hello,jhh");
}
}