我做了连接到tcp流服务器的简单应用程序(汽车中的OBD wifi连接)。 它连接并且运行良好 - 我可以发送消息并从汽车获得答案。现在我想从回答中只读取指定的数据。当我向汽车发送请求时,例如01041,它会回答这样的事情:
搜索:好的
41 04 7F
我想创建一个只包含此答案的最后一个字节的变量。在这个例子中它将是7F。我想这样做因为我想在Label中提供这些数据。所以我需要在这个示例行中跳过搜索并跳过第2行中的前2个字节以仅获得7F。我怎么能这样做?
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.0.10", 35000, &readStream, &writeStream);
self.inputStream = objc_unretainedObject(readStream);
self.outputStream = objc_unretainedObject(writeStream);
[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream open];
[self.outputStream open];
}
- (IBAction)Connect:(id)sender {
[self initNetworkCommunication];
}
- (IBAction)Play:(id)sender {
NSString *response = [NSString stringWithFormat:@"01041\r\n"];
[NSThread sleepForTimeInterval:0.05];
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSUTF8StringEncoding]];
}
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
switch (eventCode) {
case NSStreamEventOpenCompleted:
[self.logTextView setText:[self.logTextView.text stringByAppendingString:@"Stream opened\n"]];
break;
case NSStreamEventHasBytesAvailable:
if (aStream == self.inputStream) {
uint8_t buffer[1024];
long len;
while ([self.inputStream hasBytesAvailable]) {
len = [self.inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
//NSString *oborty = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
if (nil != output) {
[self.logTextView setText:[self.logTextView.text stringByAppendingString:output]];
[self.RPM setText:[self.RPM.text stringByAppendingString:output]];
}
}
}
}
break;
case NSStreamEventErrorOccurred:
[self.logTextView setText:[self.logTextView.text stringByAppendingString:@"Can not connect to the host!"]];
break;
case NSStreamEventEndEncountered:
break;
default:
NSLog(@"Unknown event");
}
}
- (IBAction)sendCode:(id)sender {
NSString *command = self.commandTextField.text;
NSString *response = [NSString stringWithFormat:@"%@\r\n", command];
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSUTF8StringEncoding]];
[self.outputStream write:[data bytes] maxLength:[data length]];
}
@end
我在http://www.raywenderlich.com教程的帮助下完成了tcp连接,所以我不太了解解决我的问题。
这一行[self.RPM setText:[self.RPM.text stringByAppendingString:output]];在Label中显示答案,但它显示了一切。我想我需要创建新的变量输出并以某种方式编辑它,但我不知道如何