public class MyClient {
public static void main (String[] args) {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class).handler(new MyClientInitializer());
ChannelFuture future = null;
try {
Channel channel = bootstrap.connect("localhost", 8899).sync().channel();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
channel.writeAndFlush(br.readLine() + "\r\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
group.shutdownGracefully();
}
}
}
1.Client端为什么没有bossGroup?只有workerGroup
因为客户端不需要accept,直接用worker连接到服务器就可以。
2.为什么不用new NioEventLoopGroup(1)?而用new NioEventLoopGroup()呢?
设置为一个线程也可以,只不过这一个线程既处理连接事件,又处理读写事件,那有多个行不行呢?多个也可以,当调用一些方法时,或者处理timeEvent,就会调用next(),这时就增加了性能。
如果使用业务线程调用了write方法,那么netty会检查是否在事件循环组中,如果不在,那么封装成一个任务丢到线程组的队列中。
private void write(Object msg, boolean flush, ChannelPromise promise) {
...
final AbstractChannelHandlerContext next = findContextOutbound(flush ?
(MASK_WRITE | MASK_FLUSH) : MASK_WRITE);
final Object m = pipeline.touch(msg, next);
EventExecutor executor = next.executor();
if (executor.inEventLoop()) {
if (flush) {
next.invokeWriteAndFlush(m, promise);
} else {
next.invokeWrite(m, promise);
}
} else {
final WriteTask task = WriteTask.newInstance(next, m, promise, flush);
if (!safeExecute(executor, task, promise, m, !flush)) {
// We failed to submit the WriteTask. We need to cancel it so we decrement the pending bytes
// and put it back in the Recycler for re-use later.
//
// See https://github.com/netty/netty/issues/8343.
task.cancel();
}
}
}
Unpooled类
Netty 提供一个专门用来操作缓冲区(即 Netty 的数据容器)的工具类。说白了就是一个工具类,使用门面模式,可以创建池化和非池化的ByteBuf,屏蔽了细节。