2014-02-24 77 views
1

全部,iOS发送命令到网络服务器

我有一个OBDII设备,它有一个网络服务器。我通过wifi连接。 我想创建一个应用程序来发送命令并读取从设备收到的数据。

我首先使用Terminal进行测试。我使用telnet会话进行连接,并可以发送一个命令(0104)并获得响应。这工作正常。

现在,我想创建一个应用程序来做同样的事情。 我知道我可以连接使用:

- (void)initNetworkCommunication { 
    CFReadStreamRef readStream; 
    CFWriteStreamRef writeStream; 
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.0.10", 35000, &readStream, &writeStream); 
    inputStream = (NSInputStream *)readStream; 
    outputStream = (NSOutputStream *)writeStream; 
    [inputStream setDelegate:self]; 
    [outputStream setDelegate:self]; 

    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
    [inputStream open]; 
    [outputStream open]; 
} 

连接工作正常。
然后,我想发送一个命令。我使用这个:

- (IBAction)sendCommand:(id)sender { 
    NSString *response = [NSString stringWithFormat:@"%@", commandText.text]; 
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]]; 
    [outputStream write:[data bytes] maxLength:[data length]]; 
} 

但我没有得到一个正确的答案,我得到一个?背部。所以设备不能识别命令...
我在做什么错了?这是错误的格式吗?它不应该是一个字符串?或者它应该与ASCII不同?

我已经试着把\ r放在命令的末尾,但这并没有帮助。

回答

1

解决方案:

用附加数据发送数据\ r \ n。 还可以更改编码采用UTF编码,但这不是强制性的?

- (IBAction)sendCommand:(id)sender { 
    NSString *response = [NSString stringWithFormat:@"%@\r\n", commandText.text]; 
    NSLog(@"Response send: %@", response); 
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSUTF8StringEncoding]]; 
    NSInteger bytesWritten = [outputStream write:[data bytes] maxLength:[data length]]; 

} 
0

...中有一个网络服务器。我通过wifi连接...

如果是这样的话,人们会认为最好的解决方案将是一个高层次的解决方案。使用NSURLRequest发送您的请求,并将数据重新写入NSHTTPURLResponse。让iOS照顾你的HTTP资料。如果这不起作用,那么你的设备的服务器不能称为Web服务器。