我在应用商店中有一个iOS应用。我正在为此开发一些新功能。我正在研究称重机和使用telnet连接在系统中注册重量的要求。 使用以下代码,我与称重机建立telnet连接
- (void)initNetworkCommunication {
uint portNo = 23;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"227.3.4.56", portNo, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
[inputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];}
委托方法中接收到的数据
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
uint8_t buffer[1024];
int len;
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened now");
break;
case NSStreamEventHasBytesAvailable:
NSLog(@"has bytes");
if (theStream == inputStream) {
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
if (nil != output) {
NSLog(@"server said: %@", output);
}
}
}
} else {
NSLog(@"it is NOT theStream == inputStream");
}
break;
case NSStreamEventHasSpaceAvailable:
NSLog(@"Stream has space available now");
break;
case NSStreamEventErrorOccurred:
NSLog(@"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
break;
default:
NSLog(@"Unknown event %i", streamEvent);
}}
由于该线程被阻塞并且无法执行进一步的代码,因此称重机会在几秒钟内连续发布相同的数据。为了避免这种情况,我要做的是一旦我第一次在NSStreamEventHasBytesAvailable中获取数据,就关闭输入流。
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
uint8_t buffer[1024];
int len;
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened now");
break;
case NSStreamEventHasBytesAvailable:
NSLog(@"has bytes");
if (theStream == inputStream) {
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
if (nil != output) {
NSLog(@"server said: %@", output);
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
}
}
} else {
NSLog(@"it is NOT theStream == inputStream");
}
break;
case NSStreamEventHasSpaceAvailable:
NSLog(@"Stream has space available now");
break;
case NSStreamEventErrorOccurred:
NSLog(@"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
break;
default:
NSLog(@"Unknown event %i", streamEvent);
}}
问题说明
关闭连接后,当我尝试在重新连接后下次尝试获取数据时,它总是给出空白响应,并且连接关闭。始终进行重新连接时,我需要数据。请指导