============================================================
詳解iPhone 下AsyncSocket網絡庫編程是本文要介紹的內容,iphone的標準推薦CFNetwork C庫編程.但是編程比較煩躁。在其它OS往往用類來封裝的對Socket函數的處理。比如MFC的CAsysncSocket.在iphone也有類似於開源項目.cocoa AsyncSocket庫
官方網站:https://code.google.com/p/cocoaasyncsocket/
這裡隻上例子,自己在項目中使用的,絕對能使用,如果有疑問,歡迎留言討論。
—————-
註意,CAsysncSocket已經將tcp、udp的連接異步化處理,所以你隻管在主線程調用即可
將AsyncSocket.h AsyncSocket.m 導入到你的工程中,
在自己建立的util中,加入一下代碼
[cpp]
01.#pragma mark tcp
02.- (void) connectToHost:(NSString*)host port:(int)port {
03. socket = [[AsyncSocket alloc] initWithDelegate:self]; //設置回調的delegate
04. //TODO 這裡需要在退出局域網模式下斷開
05. [socket disconnect]; //斷開tcp連接
06.// socket
07. NSLog(@"tcp connecting to host:%@,port:%d",host,port);
08. @try {
09. [socket connectToHost:host onPort:port error:nil];
10. [socket readDataWithTimeout:-1 tag:1]; //這隻超時,如果timeout為負數,則永遠不超時
11. }
12. @catch (NSException *exception) { //異常處理
13. NSLog(@"connect exception %@,%@", [exception name], [exception description]);
14. }
15.}
16.//相應的回調函數
17.- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
18. NSLog(@"did connect to host %@:%d", host, port);
19.}
20.- (void)sendMessage:(NSString*)msg {
21. NSLog(@"tcp send msg:%@", msg);
22. [socket readDataWithTimeout:SOCKET_TIMEOUT tag:1];
23. [socket writeData:[msg dataUsingEncoding:NSUTF8StringEncoding] withTimeout:SOCKET_TIMEOUT tag:1];
24.}
25.- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
26. NSString* message = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]autorelease];
27. NSLog(@"%f receive ReadData is: %@",[[NSDate date] timeIntervalSince1970],message);
28.
29.}
30.-(NSTimeInterval)onSocket:(AsyncSocket *)sock shouldTimeoutReadWithTag:(long)tag elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length{
31. NSLog(@"onSocket:shouldTimeout-ReadWithTag:———–");
32. return 0;
33.}
34.-(NSTimeInterval)onSocket:(AsyncSocket *)sock shouldTimeoutWriteWithTag:(long)tag elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length{
35. NSLog(@"onSocket:shouldTimeout-WriteWithTag:———–");
36. return 0;
37.}
38.
39.-(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag{
40. NSLog(@"didWriteDataWithTag tag:%ld",tag);
41.}
42.-(void)onSocketDidDisconnect:(AsyncSocket *)sock{
43. NSLog(@"onSocketDidDisconnect sock:%@",sock);
44. [viewController onLocalDisconnect:0];
45.
46.}
#pragma mark tcp
– (void) connectToHost:(NSString*)host port:(int)port {
socket = [[AsyncSocket alloc] initWithDelegate:self]; //設置回調的delegate
//TODO 這裡需要在退出局域網模式下斷開
[socket disconnect]; //斷開tcp連接
// socket
NSLog(@"tcp connecting to host:%@,port:%d",host,port);
@try {
[socket connectToHost:host onPort:port error:nil];
[socket readDataWithTimeout:-1 tag:1]; //這隻超時,如果timeout為負數,則永遠不超時
}
@catch (NSException *exception) { //異常處理
NSLog(@"connect exception %@,%@", [exception name], [exception description]);
}
}
//相應的回調函數
– (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
NSLog(@"did connect to host %@:%d", host, port);
}
– (void)sendMessage:(NSString*)msg {
NSLog(@"tcp send msg:%@", msg);
[socket readDataWithTimeout:SOCKET_TIMEOUT tag:1];
[socket writeData:[msg dataUsingEncoding:NSUTF8StringEncoding] withTimeout:SOCKET_TIMEOUT tag:1];
}
– (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
NSString* message = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]autorelease];
NSLog(@"%f receive ReadData is: %@",[[NSDate date] timeIntervalSince1970],message);
}
-(NSTimeInterval)onSocket:(AsyncSocket *)sock shouldTimeoutReadWithTag:(long)tag elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length{
NSLog(@"onSocket:shouldTimeout-ReadWithTag:———–");
return 0;
}
-(NSTimeInterval)onSocket:(AsyncSocket *)sock shouldTimeoutWriteWithTag:(long)tag elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length{
NSLog(@"onSocket:shouldTimeout-WriteWithTag:———–");
return 0;
}
-(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag{
NSLog(@"didWriteDataWithTag tag:%ld",tag);
}
-(void)onSocketDidDisconnect:(AsyncSocket *)sock{
NSLog(@"onSocketDidDisconnect sock:%@",sock);
[viewController onLocalDisconnect:0];
}