Server:
public class HelloServer {
public static void main(String[] args) {
// 服务器端启动器,将下面的组件进行启动
new ServerBootstrap()
// 2.BossEventGroup, WorkerEventGroup
// 检查IO事件
.group(new NioEventLoopGroup())
// 选择NIO, ServerSocketChannel实现
.channel(NioServerSocketChannel.class)
// 分工boss处理连接,worker处理读写
.childHandler(
// 和客户端通信的通道,初始化,添加别的handler
new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
// 解码的handler
ch.pipeline().addLast(new StringDecoder());
// 自定义handler
ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 打印上一步转化的字符串
System.out.println(msg);
}
});
}
})
.bind(8080);
}
}
Client:
public class HelloClient {
public static void main(String[] args)throws Exception {
new Bootstrap()
.group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringEncoder());
}
})
.connect(new InetSocketAddress("localhost", 8080))
// 阻塞方法
.sync()
// 代表连接对象
.channel()
// 发数据
// 收发数据都走handler
.writeAndFlush("hello, world");
}
}
EventLoop:事件循环:处理channel上的io事件,处理数据的工人
pipline:处理数据的工序:inbound,outbound,合在一起为pipLine
EventLoopGroup:事件循环组