概述
NioSocketChannel就是nio中的SocketChannel的封装,所以它肯定会提供了SocketChannel对象的创建、连接、端口绑定、关闭等操作,netty客户端和服务端都有用到这个对象。
public NioSocketChannel() {//类被反射加载的时候调用该无参构造函数
this(DEFAULT_SELECTOR_PROVIDER);
}
public NioSocketChannel(SelectorProvider provider) {
this(newSocket(provider));//创建SocketChannel并赋值
}
public NioSocketChannel(SocketChannel socket) {
this(null, socket);
}
public NioSocketChannel(Channel parent, SocketChannel socket) {
super(parent, socket);
config = new NioSocketChannelConfig(this, socket.socket());
}
//创建SocketChannel客户端channel
private static SocketChannel newSocket(SelectorProvider provider) {
try {
//创建nio的SocketChannel对象
return provider.openSocketChannel();
} catch (IOException e) {
throw new ChannelException("Failed to open a socket.", e);
}
}
//客户端跟服务端建立连接
@Override
protected boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
if (localAddress != null) {
doBind0(localAddress);//绑定地址
}
boolean success = false;
try {
boolean connected = SocketUtils.connect(javaChannel(), remoteAddress);//跟远程地址建立连接
if (!connected) {
selectionKey().interestOps(SelectionKey.OP_CONNECT);
}
success = true;
return connected;
} finally {
if (!success) {
doClose();
}
}
}
private void doBind0(SocketAddress localAddress) throws Exception {
if (PlatformDependent.javaVersion() >= 7) {
SocketUtils.bind(javaChannel(), localAddress);//绑定地址
} else {
SocketUtils.bind(javaChannel().socket(), localAddress);
}
}
public abstract class AbstractNioChannel extends AbstractChannel {
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
super(parent);
this.ch = ch;//在io.netty.channel.socket.nio.NioServerSocketChannel.doReadMessages中调用 在NioSocketChannel实例化时候也会调用
this.readInterestOp = readInterestOp;//bossGroup是NioServerSocketChannel写死OP_ACCEPT事件 workgroup是AbstractNioByteChannel写死OP_READ事件
try {
ch.configureBlocking(false);//设置为非阻塞
} catch (IOException e) {
try {
ch.close();
} catch (IOException e2) {
logger.warn(
"Failed to close a partially initialized socket.", e2);
}
throw new ChannelException("Failed to enter non-blocking mode.", e);
}
}
}
总结就是:
1、netty客户端 创建SocketChannel
2、netty客户端 建立远程连接
3、netty服务端获取到客户端SocketChannel之后 包装成NioSocketChannel对象也会用到相关构造函数
最后
以上就是激情万宝路为你收集整理的netty学习8:NioSocketChannel源码分析的全部内容,希望文章能够帮你解决netty学习8:NioSocketChannel源码分析所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复