I am working on printing features using socket programming in iOS. I use the following code to open threads and perform read and write operations. When threads open, the delegate receives a call for an open event for both input and output streams. I also get the NSStreamEventHasSpaceAvailable event, in which I perform a write operation and the NSStreamEventHasBytesAvailable event, where I perform a read operation. The write operation is successful for the first 2 times, after which I get an event with bytes, where I try to perform a read operation. Each time I get -1 as read bytes and receive an NSStreamEventErrorOccurred event with the message "Operation could not be completed. Connection reset by peer" for NSInputStream, followed by the same event for NSOutputStream, and while writing to third time. Sometimes I even get a Broken Pipe error.
CFReadStreamRef readStream; CFWriteStreamRef writeStream; CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"123.123.12.12",DEFAULT_LPR_PORT, &readStream, &writeStream); self.inputStream = (__bridge NSInputStream *)readStream; self.outputStream = (__bridge NSOutputStream *)writeStream; [self.inputStream setDelegate:self]; [self.outputStream setDelegate:self]; [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [self.inputStream open]; [self.outputStream open];
Stream event handler - Delagate method code Reading bytes is always -1.
case NSStreamEventHasBytesAvailable: { NSLog(@"NSStreamEventHasBytesAvailable"); if (theStream == inputStream) { uint8_t buffer[1024]; int len = 0; while ([self.inputStream hasBytesAvailable]) { len = [self.inputStream read:buffer maxLength:sizeof(buffer)]; NSLog(@"bytes read len --- :%d ",len); if (len > 0) { NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding]; if (nil != output) { NSLog(@"bytes value: %@", output); } } } } } break;
Errror:
2013-09-18 12:27:36.424 SPConnector[1936:907] stream:handleEvent: : <__NSCFInputStream: 0x1e07b0e0> 2013-09-18 12:27:36.428 SPConnector[1936:907] NSStreamEventErrorOccurred localizedDescription --- The operation couldn't be completed. Connection reset by peer 2013-09-18 12:27:36.430 SPConnector[1936:907] NSStreamEventErrorOccurred domain --- NSPOSIXErrorDomain 2013-09-18 12:27:36.431 SPConnector[1936:907] NSStreamEventErrorOccurred Code --- :54 2013-09-18 12:27:36.432 SPConnector[1936:907] stream:handleEvent: : <__NSCFOutputStream: 0x1e07b170> 2013-09-18 12:27:36.433 SPConnector[1936:907] NSStreamEventErrorOccurred localizedDescription --- The operation couldn't be completed. Connection reset by peer 2013-09-18 12:27:36.434 SPConnector[1936:907] NSStreamEventErrorOccurred domain --- NSPOSIXErrorDomain 2013-09-18 12:27:36.435 SPConnector[1936:907] NSStreamEventErrorOccurred Code --- :54
Can someone tell me what could be causing the problem?
source share