IOS socket编程 - NSStream不工作
问题描述:
我使用的是被称为具有IP地址的WiFly设备:169.254.1.1和端口2000年。我试图连接到该设备通过iOS应用程序。我用下面的代码连接:IOS socket编程 - NSStream不工作
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
UInt32 port = 2000;
CFStringRef host = CFSTR("169.254.1.1");
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host, port, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
// set the delegates to this view controller
[inputStream setDelegate:self];
[outputStream setDelegate:self];
// Set run loops to continuous receive information
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
// Finally, open the connection
[inputStream open];
[outputStream open];
然后我用下面的处理流事件:
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
NSLog(@"stream event %i", streamEvent);
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
uint8_t buffer[1024];
int len;
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);
[self messageReceived:output];
}
}
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(@"Can't connect to server");
break;
case NSStreamEventEndEncountered:
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
break;
default:
NSLog(@"Unknown event");
}
所以,我可以看到,前两个流被正确打开。然后立即跟踪一个流事件4,从我的理解中可以预料到这一点。然而,我再尝试调用一个函数:
- (IBAction)moveForward
{
NSLog(@"move forward called");
NSString *response = [NSString stringWithFormat:@"2"];
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
}
应当从一个Arduino UNO通过wifly返回“前进”。但是,当我点击时,出于某种原因,我得到另一个NSStreamEvent 4。我还通过终端telnetted在将该设备与:
的telnet 169.254.1.1 2000
并随后键入“2” ...这返回所需的“正向”立即。从iPad的角度来看,我做错了什么?
此外,该代码是工作几个星期前。但是一旦我更新了模拟器,它就停止工作......连接正常打开,但是Arduino设备似乎没有从iOS获得输出。
非常感谢帮助!
答
尝试更换 的NSString *响应= [NSString的stringWithFormat:@ “2”]; 与此 的NSString *响应= [NSString的stringWithFormat:@ “%d”,2]; in moveForward方法。
答
NSStreamEvent 4是NSStreamEventHasSpaceAvailable。 在发送数据之前,您必须等到输出流具有可用空间。