【发布时间】:2012-03-06 14:23:32
【问题描述】:
我是 iOS 编程的新手 - 我需要一些帮助来解决我的问题... 我花了很多时间试图找到解决这个问题的方法 - 但没有任何成功......
我正在编写一个非常简单的应用程序(在 iPad 上),它将通过一些 TCP 命令发送到我的服务器。服务器已经配置好并且工作正常。我可以在我的 iPad 上使用 pTerm 连接到它,在通过 RAW TCP 或 telnet 成功连接后,我可以将请求发送到我的服务器,如下所示:
#100进入
它有效..
但是当我尝试在我的应用程序上执行此操作时 - 它不起作用,这似乎是与服务器的行尾信息有关的问题(通常通过按 enter 键完成)。 服务器配置在 192.168.1.220,端口 2000。
单击重置按钮后,它应该向服务器发送命令 - 但我在服务器端看不到任何内容...
我的 .h 文件看起来:
#import <UIKit/UIKit.h>
NSInputStream *inputStream;
NSOutputStream *outputStream;
@interface ViewController : UIViewController <NSStreamDelegate>
@property (weak, nonatomic) IBOutlet UIButton *resetbutton;
@property (strong, nonatomic) IBOutlet UIView *viewController;
- (IBAction)resetbuttonclick:(id)sender;
@end
我的 .m 文件:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize resetbutton;
@synthesize viewController;
- (void) viewDidLoad
{
[self initNetworkCommunication];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void) viewDidUnload
{
[self setViewController:nil];
[self setResetbutton:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)initNetworkCommunication
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.1.220", 2000, &readStream, &writeStream);
inputStream = objc_unretainedObject(readStream);
outputStream = objc_unretainedObject(writeStream);
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
- (void)sendMessage
{
NSString *response = [NSString stringWithFormat:@"#100\n"];
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
}
- (IBAction)resetbuttonclick:(id)sender
{
[self initNetworkCommunication];
[self sendMessage];
}
@end
非常感谢您的帮助。
【问题讨论】:
标签: objective-c ios sockets tcp