简体   繁体   中英

iOS send command to web server

All,

I have an OBDII device which has a webserver in it. I connect via wifi. I want to create an app to send commands and read the data received from the device.

I first test it using Terminal. I connect using a telnet session and can send a command (0104) and I get the respons. This works fine.

Now, I want to create an app to do the same. I know I can connect using:

- (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];
}

The connection works fine.
Then, I want to send a command. I use this:

- (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]];   
}

But I don't get a correct answer, I get a ? back. So the device does not recognize the command...
What am I doing wrong? Is it the wrong format? Shouldn't it be a String? Or should it be different than ASCII?

I already tried to put \\r at the end of the command, but this does not help.

Solution:

Send the data with addition \\r\\n. Can also change encoding in UTF encoding but this is not mandatory...

- (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]];

}

...has a webserver in it. I connect via wifi...

If that's the case, one would think the best solution would be a high-level one. Use NSURLRequest to send your request, and get the data back in an NSHTTPURLResponse . Let iOS take care of the HTTP stuff for you. If that doesn't work, then your device's server can't really be called a web server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM