我是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
非常感谢你的帮助。
答案 0 :(得分:2)
您正在启动连接两次,从[self initNetworkCommunication];
方法中删除行resetbutonclick
。
答案 1 :(得分:0)
立即注意到的一件事是你没有任何流事件的使用者 - 这很奇怪。你怎么知道这个联系已经建立了?
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
iPhone Network Programming中的代码经过测试并正常工作,如果您愿意阅读这些文章。
答案 2 :(得分:0)
也许你可以通过使用额外的库来避免这些问题? (抽象在上面) 我使用CocoaAsyncSocket。这很简单舒适。