我使用的是被稱爲具有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獲得輸出。
非常感謝幫助!