2012-03-06 113 views
1

我是iOS编程的新手 - 我需要一些帮助来解决我的问题... 我花了很多时间试图找到解决这个问题 - 但没有任何成功...TCP套接字通信问题

我正在写一个非常简单的应用程序(在iPad上),它将通过几个TCP命令发送到我的服务器。服务器已配置并正常工作。我可以pTerm连接到它在我的iPad,并在RAW TCP或telnet成功地连接后,我可以将请求发送到我的服务器看起来就像是:

进入

,它作品..

但是,当我试图做我的应用程序 - 它不起作用,它似乎是一个服务器行结束信息的问题(通常通过推输入键完成)。 服务器上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 

非常感谢您的帮助。

回答

2

您正在启动连接两次,从resetbutonclick方法中删除行[self initNetworkCommunication];

+0

好的,我删除它。我也检查了 - 那个#100发送 - 但我不知道如何发送行结束char - chr(13)。当 – user1252412 2012-03-06 16:48:42

+0

什么时候?所以它现在正在工作,但你想发送另一个角色吗? CHR(13)? – fbernardo 2012-03-06 16:58:58

0

有一件事立即注意到你没有任何流事件掠夺者 - 这很奇怪。你怎么知道这个连接已经建立?

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode

iPhone Network Programming的代码进行测试和工作,如果你愿意读低谷中的文章。

0

也许你可以通过使用额外的库避免这种问题? (抽象顶部) 我使用CocoaAsyncSocket。这很简单,舒适。