[英]iOS send command to web server
All, 所有,
I have an OBDII device which has a webserver in it. 我有一个带Web服务器的OBDII设备。 I connect via wifi.
我通过wifi连接。 I want to create an app to send commands and read the data received from the device.
我想创建一个应用程序来发送命令并读取从设备接收的数据。
I first test it using Terminal. 我首先使用Terminal对其进行测试。 I connect using a telnet session and can send a command (0104) and I get the respons.
我使用telnet会话进行连接,可以发送命令(0104),并且得到响应。 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?
还是应该不同于ASCII?
I already tried to put \\r at the end of the command, but this does not help. 我已经尝试将\\ r放在命令末尾,但这无济于事。
Solution: 解:
Send the data with addition \\r\\n. 发送带有附加\\ r \\ n的数据。 Can also change encoding in UTF encoding but this is not mandatory...
也可以更改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]];
}
...has a webserver in it.
...其中有一个网络服务器。 I connect via wifi...
我通过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
. 使用
NSURLRequest
发送您的请求,并在NSHTTPURLResponse
获取数据。 Let iOS take care of the HTTP stuff for you. 让iOS为您处理HTTP事务。 If that doesn't work, then your device's server can't really be called a web server.
如果那不起作用,那么您设备的服务器就不能真正称为Web服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.