首页 > 代码库 > socket通讯----GCDAsyncSocke 解读
socket通讯----GCDAsyncSocke 解读
GCDAsyncSocke 分为
一. Configuration 配置
1.1代理的设置
1.2线程的设置
1.3IPV4,IPV6的设置
二. Accepting 接收
2.1.监听端口起点
- (BOOL)acceptOnPort:(uint16_t)port error:(NSError **)errPtr
{
return [self acceptOnInterface:nil port:port error:errPtr];
}
- (BOOL)acceptOnInterface:(NSString *)inInterface port:(uint16_t)port error:(NSError **)errPtr
{
LogTrace();
// Just in-case interface parameter is immutable.
//防止参数被修改
NSString *interface = [inInterface copy];
__block BOOL result = NO;
__block NSError *err = nil;
// CreateSocket Block
// This block will be invoked within the dispatch block below.
//创建socket的Block
int(^createSocket)(int, NSData*) = ^int (int domain, NSData *interfaceAddr) {
//创建TCP的socket
int socketFD = socket(domain, SOCK_STREAM, 0);
//一系列错误判断
...
// Bind socket
//用本地地址去绑定
status = bind(socketFD, (const struct sockaddr *)[interfaceAddr bytes], (socklen_t)[interfaceAddr length]);
//监听这个socket
//第二个参数是这个端口下维护的socket请求队列,最多容纳的用户请求数。
status = listen(socketFD, 1024);
return socketFD;
};
// Create dispatch block and run on socketQueue
dispatch_block_t block = ^{ @autoreleasepool {
//一系列错误判断
...
//判断ipv4 ipv6是否支持
...
//得到本机的IPV4 IPV6的地址
[self getInterfaceAddress4:&interface4 address6:&interface6 fromDescription:interface port:port];
...
//判断可以用IPV4还是6进行请求
...
// Create accept sources
//创建接受连接被触发的source
if (enableIPv4)
{
//接受连接的source
accept4Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, socket4FD, 0, socketQueue);
//事件句柄
dispatch_source_set_event_handler(accept4Source, ^{ @autoreleasepool {
//拿到数据,连接数
unsigned long numPendingConnections = dispatch_source_get_data(acceptSource);
LogVerbose(@"numPendingConnections: %lu", numPendingConnections);
//循环去接受这些socket的事件(一次触发可能有多个连接)
while ([strongSelf doAccept:socketFD] && (++i < numPendingConnections));
}});
//取消句柄
dispatch_source_set_cancel_handler(accept4Source, ^{
//...
//关闭socket
close(socketFD);
});
//开启source
dispatch_resume(accept4Source);
}
//ipv6一样
...
//在scoketQueue中同步做这些初始化。
if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
block();
else
dispatch_sync(socketQueue, block);
//...错误判断
//返回结果
return result;
}
三. Connecting 连接
四. Disconnecting 断开
五. Diagnostics 诊断
六. Reading 读取
七. Writing 写入
八. Security 安全
九. Advanced
十. Utilities
socket通讯----GCDAsyncSocke 解读