2012-03-06 95 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。這很簡單,舒適。