GCDAsyncSocket 地址: https://github.com/robbiehanson/CocoaAsyncSocket/
使用方法:
创建:
asyncsocket = [[GCDAsyncSocket alloc] initWithDelegate:
self
delegateQueue:dispatch_get_main_queue()];
|
这里我们让所有的回调执行都发生在主线程的queue里,当然我们可以传一个专用的queue.
连接 :
NSError
*err =
nil
;
if
(![asyncsocket connectToHost:@
"deusty.com"
onPort:80 error:&err])
// Asynchronous!
{
//该方法异步,返回错误是因为 delegate没设置等
NSLog
(@
"I goofed: %@"
, err);
}
|
该方法会立刻返回,当成功连接上,delegate 的 socket:didConnectToHost:port: 方法会被调用.
- (
void
)socket:(GCDAsyncSocket *)sender didConnectToHost:(
NSString
*)host port:(UInt16)port
{
NSLog
(@
"Cool, I'm connected! That was easy."
);
}
|
有几种不同的连接方法,比如带超时的.。。。
虽然这个时候可能 socket 还没连接上,但是我们依然可以投递 读/写 请求:
[asyncSocket readDataToLength:LENGTH_HEADER withTimeout:-1 tag:TAG_HEADER];
|
这样读请求会自动进入了队列,当socket 连接上后,请求会自动出队被执行。(这里假设先读一个包头,再根据长度接收包体,这个读操作完成后 socket:didReadData:withTag: 会被调用)
当然我们可以投递多个读写操作而不必等待上一个完成.
[asyncSocket writeData:msgHeader withTimeout:-1 tag:TAG_HEADER];
[asyncSocket writeData:msgBody withTimeout:-1 tag:TAG_BODY];
|
上面的操作均为异步。下面为操作完成的委托方法:
read:
- (void)socket:(GCDAsyncSocket *)sender didReadData:(NSData *)data withTag:(long)tag { if (tag == TAG_HEADER) { int bodyLength = [self parseHeader:data]; [socket readDataToLength:bodyLength withTimeout:-1 tag:TAG_RESPONSE_BODY]; } else if (tag == TAG_RESPONSE_BODY) { // Process the response [self handleResponseBody:data]; // Start reading the next response [socket readDataToLength:headerLength withTimeout:-1 tag:TAG_FIXED_LENGTH_HEADER]; } } //还有另一个读方法, // [asyncSocket readDataToData:msgSeparator withTimeout:TIMEOUT_NONE tag:TAG_CAPABILITIES]; // 读当遇到一个指定的分隔符后操作返回。比如用作 http, 因为http 每个消息都会有一个@"\r\n\r\n" 结尾标志.
//如果想跟踪进度 socket: didReadPartialDataOfLength: tag: 用这个
write:
- (
void
)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(
long
)tag
{
if
(tag ==TAG_HEADER) <br>
NSLog
(@
"TAG_HEADER request sent"
);
|
else
if
(tag ==TAG_BODY) <br>
NSLog
(@
"TAG_BODY request sent"
);
|
}
|
断开释放一个连接实例
[asyncSocket setDelegate:
nil
delegateQueue:
NULL
];
[asyncSocket disconnect];
[asyncSocket release];
|
相关的delegate 方法(回调)
socket: didConnectToHost: port:<br>
socket: didReadData: withTag:
socket: didReadPartialDataOfLength: tag:
socket: shouldTimeoutReadWithTag: elapsed: bytesDone:<br>
socket: didWriteDataWithTag:
socket: didWritePartialDataOfLength: tag:
socket: shouldTimeoutWriteWithTag: elapsed: bytesDone:<br>
socketDidSecure:<br>
socket: didAcceptNewSocket:<br>
newSocketQueueForConnectionFromAddress: onSocket:<br>
socketDidCloseReadStream:<br>
socketDidDisconnect: withError:
|