我尝试使用 NSStream 从/向 Socket 读取和写入数据。这是我的连接代码:
- (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)
为什么读取方法返回这么大的值?它真的读了那么多字节吗?(我不这么认为):)
PS: Socket Stream 服务器没问题。它也向其他客户端读写数据,没有问题。