我是 iOS 编程的新手 - 我需要一些帮助来解决我的问题... 我花了很多时间试图找到解决这个问题的方法 - 但没有成功......
我正在编写一个非常简单的应用程序(在 iPad 上),它将向我的服务器发送一些 TCP 命令。服务器已经配置好并且工作正常。我可以在我的 iPad 上使用 pTerm 连接到它,在通过 RAW TCP 或 telnet 成功连接后,我可以将请求发送到我的服务器,如下所示:
#100
enter
它起作用了..
但是当我尝试在我的应用程序上执行此操作时 - 它不起作用,这似乎是发送到服务器的行尾信息的问题(通常通过按 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
非常感谢您的帮助。
最佳答案
您要启动连接两次,从 resetbutonclick
方法中删除行 [self initNetworkCommunication];
。
关于objective-c - TCP套接字通信问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9585498/