2012-01-31 91 views
0

這是我在stackoverflow上的第一個具體問題,因爲我找不到任何對我的問題有用的解決方案。 我需要iPhone和OSX工作站(作爲TCP服務器)之間的低級套接字連接,以交換諸如圖片或音頻文件等媒體數據。所以我認爲AsyncSockets是一個很好的選擇,可以讓它工作。我經常用它來進行一些微小的字節通信。AsyncSockets - ReadToData - 不能像預期的那樣工作

我的問題是,我想用一種頭/協議告訴服務器有多少數據字節仍在管道中。 像「hello world」這樣的簡單通信工作正常,所以沒有連接問題。

移動設備(即想發送圖片)執行以下操作。

[self setHost:@"172.22.42.207"]; 
self.socket = [[[AsyncSocket alloc] initWithDelegate:self] autorelease]; 

NSError *err = nil; 
[[self socket] connectToHost:self.host onPort:5009 error:&err]; 

...

NSData *t = UIImagePNGRepresentation(test); 

NSString *header = [NSString stringWithFormat:@"%i", t.length]; 
NSMutableData *headerData = [[header dataUsingEncoding:NSUTF8StringEncoding] mutableCopy]; 
[headerData appendBytes:[AsyncSocket CRLFData] length:[[AsyncSocket CRLFData] length]]; 

[[self socket] writeData:headerData withTimeout:-1 tag:0]; 

服務器監聽這種方式:

AsyncSocket *s = [[AsyncSocket alloc] initWithDelegate:self]; 
NSError *err = nil; 
[s acceptOnPort:5009 error:&err]; 

if(err) 
    NSLog(@"EPIC FAIL...\n%@", err); 

....

- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket 
{ 
    NSLog(@"%s", __PRETTY_FUNCTION__);  
    [newSocket readDataToData:[AsyncSocket CRLFData] withTimeout:-1 tag:0]; 
} 

現在:如果我使用READDATA:withTimeout :標記它所有的作品就像一個魅力。但是,一旦我將代碼更改爲readDataToData:withTimeout:tag,要將頭從其他內容中分離出來,就不會調用onSocket:didConnectToHost:port:方法。這裏有一些漂亮的功能日誌(我將它們放置在每一個委託方法)

Client side: 
2012-01-31 13:40:32.962 AVMobile[20643:10703] -[SLViewController onSocket:didConnectToHost:port:] 
2012-01-31 13:40:32.964 AVMobile[20643:10703] -[SLViewController onSocket:didWriteDataWithTag:] 

Server side: 
2012-01-31 13:40:32.961 AVServer[20618:707] -[SLAppDelegate onSocket:didAcceptNewSocket:] 

所以,未來的想法...只是比較發送和接收的字節,所以:

Sending: <33333736 35365cba> 
Receiving: <33333736 35365cba> 

是啊......現在我的最後一個問題是:我做錯了什麼! 爲什麼不爲我工作:)?

問候&謝謝! sniperosx

回答

0

找到了解決辦法:

只要不使用-1作爲超時。 使用-1超時時,AsyncSocket正在讀取數據,直到另一方關閉連接,因此在此範圍內不會調用委託方法。

Cheerz sniperosx

[關閉]

+0

它還如果你使用readDataWithTimeout而不是readDataToData在服務器端的工作。 [newSocket readDataWithTimeout:-1 tag:tag]; – user523234 2012-02-29 14:49:12

相關問題