我嘗試使用NSStream從/向Socket讀寫數據。這裏是我的代碼用於連接:當字節可用時,NSInputStream讀取返回無符號整數最大值
- (void)connect
{
[NSStream getStreamsToHostNamed:APIC_HOST_ADDR
port:APIC_HOST_PORT
inputStream:&inStream
outputStream:&outStream];
[inStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
inStream.delegate = self;
outStream.delegate = self;
if ([inStream streamStatus] == NSStreamStatusNotOpen)
[inStream open];
if ([outStream streamStatus] == NSStreamStatusNotOpen)
[outStream open];
}
和輸入流我實現委託方法來收到事件
- (void)handleInputStreamEvent:(NSStreamEvent)eventCode
{
switch (eventCode) {
case NSStreamEventHasBytesAvailable:
{
int bytesRead;
if (data == nil) {
data = [[NSMutableData alloc] init];
}
uint8_t buf[1024];
unsigned int len = 0;
len = [inStream read:buf maxLength:1024];
if(len>0) {
@try {
[data appendBytes:(const void *)buf length:len];
}
@catch (NSException *exception) {
NSLog(@"Fail: %@", exception);
}
@finally {
NSLog(@"Finally");
bytesRead += len;
}
} else {
NSLog(@"No Buffer");
}
NSString *str = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
[str release];
[data release];
data = nil;
} break;
case NSStreamEventErrorOccurred:
{
NSError *theError = [inStream streamError];
NSLog(@"Error reading stream! ,Error %i: %@",[theError code], [theError localizedDescription]);
[self disconnect];
[self connect];
} break;
}
}
[NSStream read:maxLength:]
總是返回最大的無符號整型值。最終我得到這個錯誤:
Fail: *** -[NSConcreteMutableData appendBytes:length:]: unable to allocate memory for length (4294967295)
爲什麼閱讀mehod返回這個大的價值?它真的讀了那麼多字節嗎? (我不這麼認爲):)
PS:套接字流服務器是好的。它也讀取和寫入數據到其他客戶端也沒有問題。
@Arthur Korchagin好的,謝謝。 – leopardpan 2015-11-20 10:39:19