2013-07-25 73 views
1

我使用this (quite old) example by Apple創建了一個TCP服務器。我的服務器已啓動並正在運行,在指定的端口上監聽傳入的連接。NSInputStream無法從TCP連接讀取[TCP-Server]

一切都看起來很完美,我的客戶端應用程序可以連接到服務器,並按預期調用-stream:handleEvent:

但是當我現在寫入流時,服務器拒絕我的連接。客戶說,30字節已成功寫入。

但我的日誌說:

did read 0 Bytes from inputStream. 
data received: 
NSStreamEventErrorOccurred 
Error: Error Domain=NSPOSIXErrorDomain code=14 "The operation couldn't be completed. Bad address" 

在客戶端我用下面的代碼來建立連接:

CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"10.0.10.40", 58896, &readStream, &writeStream); 

_iStream = (__bridge NSInputStream *)readStream; 
_oStream = (__bridge NSOutputStream *)writeStream; 

[_iStream setDelegate:self]; 
[_oStream setDelegate:self]; 

[_iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
[_oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 

[_iStream open]; 
[_oStream open]; 

在服務器端,這造成插座(一CFSocketCallBack是提供)

_IPv4Socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, (CFSocketCallBack)&JWTCPServerAcceptCallBack, nil); 

然後在回調中我使用這個配對:

CFStreamCreatePairWithSocket(kCFAllocatorDefault, nativeSocketHandle, &readStream, &writeStream); 
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue); 
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue); 

然後橋樑投送到NSStreams,設置委託,安排在當前runloop並打開它們。

我不太確定爲什麼會出現這種情況,所以我不提供整個服務器代碼。這太簡單了。

當你需要一段特定的代碼或猜測它可能導致的位置時,我會在這裏發佈相應的代碼。

UPDATE

我現在做了很多的研究,我自己的代碼。我將問題追蹤到我的-stream:handleEvent方法調用。

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { 
    uint8_t *buffer = NULL; 
    NSMutableData *receivedData; 

    switch(eventCode) { 
     case NSStreamEventHasBytesAvailable: 

     if(aStream == _iStream) { 
      receivedData = [NSMutableData data]; 

      while([_iStream read:buffer maxLength:1] > 0) { 
      // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ THIS RETURNS -1 
       if([[[NSString alloc] initWithBytes:buffer length:sizeof(buffer) encoding:NSUTF8StringEncoding] isEqualToString:@"\n"]) { 
        break; 
       } 

       [receivedData appendBytes:buffer length:sizeof(buffer)]; 
      } 

      NSLog(@"Did receive %li Bytes of data: %@", [receivedData length], [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]); 
     } 
    } 
} 

更新2

我讀this great Apple Article關於TCP服務器和客戶端。我經歷了所有的步驟,並且我的程序與Apple提供的代碼幾乎完全相同。問題依然存在。

回答

2

我找到了解決方案!其實我是在宣佈緩衝區完全錯誤。因此,該錯誤消息意味着地址不是一個網絡地址,我以爲......

uint8_t *buffer = NULL; 

必須變成

uint8_t buffer[1]; 
相關問題