我正在使用一个名为WiFly的设备,其IP地址为:169.254.1.1和端口2000.我正在尝试通过iOS应用程序连接到此设备。我使用以下代码进行连接:
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。我还通过终端telnet到设备:
telnet 169.254.1.1 2000
然后键入“2”......这会立即返回所需的“前进”。从iPad的角度来看,我做错了什么?
此外,此代码几周前正在运行。但是一旦我更新了模拟器,它就停止了工作......连接正常打开,但是arduino设备似乎没有从iOS获得输出。
非常感谢帮助!
答案 0 :(得分:0)
NSStreamEvent 4是NSStreamEventHasSpaceAvailable。 您必须等到输出流有可用空间才能发送数据。
答案 1 :(得分:-1)
尝试更换 NSString * response = [NSString stringWithFormat:@“2”]; 有了这个 NSString * response = [NSString stringWithFormat:@“%d”,2]; 在moveForward方法中。