iOS 移动开发网络 part5.2:CocoaAsyncSoc
2018-01-03 本文已影响0人
破弓
_socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
- (id)initWithDelegate:(id<GCDAsyncSocketDelegate>)aDelegate delegateQueue:(dispatch_queue_t)dq socketQueue:(dispatch_queue_t)sq
{
if((self = [super init]))
{
delegate = aDelegate;
delegateQueue = dq;
socket4FD = SOCKET_NULL;
socketUrl = nil;
stateIndex = 0;
if (sq)
{
NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),
@"The given socketQueue parameter must not be a concurrent queue.");
NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),
@"The given socketQueue parameter must not be a concurrent queue.");
NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
@"The given socketQueue parameter must not be a concurrent queue.");
socketQueue = sq;
}
else
{
socketQueue = dispatch_queue_create([GCDAsyncSocketQueueName UTF8String], NULL);
}
IsOnSocketQueueOrTargetQueueKey = &IsOnSocketQueueOrTargetQueueKey;
void *nonNullUnusedPointer = (__bridge void *)self;
dispatch_queue_set_specific(socketQueue, IsOnSocketQueueOrTargetQueueKey, nonNullUnusedPointer, NULL);
readQueue = [[NSMutableArray alloc] initWithCapacity:5];
currentRead = nil;
writeQueue = [[NSMutableArray alloc] initWithCapacity:5];
currentWrite = nil;
preBuffer = [[GCDAsyncSocketPreBuffer alloc] initWithCapacity:(1024 * 4)];
alternateAddressDelay = 0.3;
}
return self;
}
GCDAsyncSocket
创建完成,可以看出,初始化方法内_socket
获取到了:
delegate
delegateQueue//调用delegate方法的队列
socketQueue//必须是串行队列,否则抛出异常;所有GCDAsyncSocket的读写全要在socketQueue内进行
readQueue
writeQueue
preBuffer//预备缓存块
alternateAddressDelay//DNS会返回连接的备选地址,首选地址连接失败后,延后连接备选地址,alternateAddressDelay就规定了延后多长时间发起第二次连接(连接备选地址的情况本文不会细作解析)
IsOnSocketQueueOrTargetQueueKey//所有GCDAsyncSocket的读写全要在socketQueue内进行,IsOnSocketQueueOrTargetQueueKey就是用于防止socketQueue重入的