一、前言
上篇博客介绍了服务端的启动源码,这篇就开始介绍客户端
二、源码分析
首先贴上客户端的简单代码~
public class SocketClient {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
.handler(new SocketClientInitializer());
ChannelFuture channelFuture = bootstrap.connect("localhost", 7878).sync();
channelFuture.channel().closeFuture().sync();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
}
设置group和server端不同的是,这里这设置一个group
public B group(EventLoopGroup group) {
if (group == null) {
throw new NullPointerException("group");
}
if (this.group != null) {
throw new IllegalStateException("group set already");
}
this.group = group;
return (B) this;
}
设置channel
public B channel(Class extends C> channelClass) {
if (channelClass == null) {
throw new NullPointerException("channelClass");
}
// server端使用的是ReflectiveChannelFactory
// 最后newChannel()后面也是通过反射来实现的了
return channelFactory(new BootstrapChannelFactory(channelClass));
}
设置handler
@SuppressWarnings("unchecked")
public B handler(ChannelHandler handler) {
if (handler == null) {
throw new NullPointerException("handler");
}
this.handler = handler;
return (B) this;
}
接着就是核心代码连接了
public ChannelFuture connect(String inetHost, int inetPort) {
return connect(new InetSocketAddress(inetHost, inetPort));
}
public ChannelFuture connect(SocketAddress remoteAddress) {
if (remoteAddress == null) {
throw new NullPointerException("remoteAddress");
}
validate();
return doConnect(remoteAddress, localAddress());
}
// 这部分代码和server绑定类似
private ChannelFuture doConnect(final SocketAddress remoteAddress, final SocketAddress localAddress) {
// 初始化和注册channel
final ChannelFuture regFuture = initAndRegister();
// 获取channel
final Channel channel = regFuture.channel();
if (regFuture.cause() != null) {
return regFuture;
}
final ChannelPromise promise = channel.newPromise();
if (regFuture.isDone()) {
doConnect0(regFuture, channel, remoteAddress, localAddress, promise);
} else {
// 为future添加一个监听器
regFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
doConnect0(regFuture, channel, remoteAddress, localAddress, promise);
}
});
}
return promise;
}
final ChannelFuture initAndRegister() {
// 创建channel
final Channel channel = channelFactory().newChannel();
try {
// 初始化channel
init(channel);
} catch (Throwable t) {
channel.unsafe().closeForcibly();
return channel.newFailedFuture(t);
}
// 注册channel
ChannelFuture regFuture = group().register(channel);
if (regFuture.cause() != null) {
if (channel.isRegistered()) {
channel.close();
} else {
channel.unsafe().closeForcibly();
}
}
return regFuture;
}
//Bootstrap channel初始化部分
void init(Channel channel) throws Exception {
// 获取通道
ChannelPipeline p = channel.pipeline();
// 为通道添加handler,这里的handler就是我们添加的ChannelInitializer类
p.addLast(handler());
// 下面的一些配置就不是很重要的了
final Map, Object> options = options();
synchronized (options) {
for (Entry, Object> e: options.entrySet()) {
try {
if (!channel.config().setOption((ChannelOption
ok,到了channel的初始化和注册完成了。继续看注册完了之后
private ChannelFuture doConnect(final SocketAddress remoteAddress, final SocketAddress localAddress) {
final ChannelFuture regFuture = initAndRegister();
final Channel channel = regFuture.channel();
if (regFuture.cause() != null) {
return regFuture;
}
final ChannelPromise promise = channel.newPromise();
if (regFuture.isDone()) {
doConnect0(regFuture, channel, remoteAddress, localAddress, promise);
} else {
// 添加监听器
regFuture.addListener(new ChannelFutureListener() {
// 将会在调用sync之后调用此方法
@Override
public void operationComplete(ChannelFuture future) throws Exception {
doConnect0(regFuture, channel, remoteAddress, localAddress, promise);
}
});
}
return promise;
}
// 调用sync()之后
private static void doConnect0(
final ChannelFuture regFuture, final Channel channel,
final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) {
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
if (regFuture.isSuccess()) {
if (localAddress == null) {
//channel: java.nio.channels.SocketChannel
// 真正连接了
channel.connect(remoteAddress, promise);
} else {
channel.connect(remoteAddress, localAddress, promise);
}
promise.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
} else {
promise.setFailure(regFuture.cause());
}
}
});
}
三、总结
总的来说,client的源码和server端的开启还是有点类似的,如果服务端的源码能大致了解,那么client比较简单的了~~~