2012-04-25 31 views
3

背景: 我製作了一個基於UDP的IPhone套接字應用程序。它在與Linux [Ubuntu]服務器通信時作爲客戶端和服務器。 我正在使用GCDAsyncUdpSocket來發送和接收數據。我的Macbook上還有一個備份服務器/客戶端應用程序,用於測試/驗證套接字通信應用程序。它只是像Linux [Ubuntu]服務器一樣。它工作完美。從iOS服務器上的UDP服務器接收數據不能在Linux服務器上運行,但是可以從macbook pro運行

問題:我無法從Linux [Ubuntu]服務器接收任何數據。

詳細信息:我可以成功將數據發送到Linux服務器,並對該數據作出反應/處理。但是當服務器發送回覆或回聲時,我的iPhone應用程序無法看到/讀取它。 我與一位Android同事開發的類似應用程序確實從服務器讀取/查看數據。 請參閱下面的代碼。乾杯!

這是它的代碼: .m文件:

-(void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    backGround.userInteractionEnabled=YES; 
    udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()]; 

    NSError *error = nil; 
    if (![udpSocket bindToPort:0 error:&error]) //check ff of dit werkt! 
    { 
     return; 
    } 
    if (![udpSocket beginReceiving:&error]) 
    { 
     return; 
    } 
} 


- (IBAction)sendData:(id)sender 
{ 
    NSString *msg = messageField.text; 
    NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding]; 
    [self sendingRealData:data]; 
} 

-(void)sendingRealData:(NSData *) Content 
{ 
    NSString *msg = [[NSString alloc] initWithData:Content encoding:NSUTF8StringEncoding]; 
    NSLog(@"msg is: %@", msg); 
    NSString *host = [self getHost]; 
    int port = [self getPort]; 

    if ((port == 65536) && (host == @"-1")) 
    { 
     NSLog(@"Port and IP are not filled in!"); 
     [self errorManag:2]; 
    } 

    else if ((port == 65536) && (host != @"-1")) 
    { 
     NSLog(@"return was -2"); 
     [self errorManag:1]; 
    } 

    else if (host == @"-1") 
    { 
     NSLog(@"return was -1"); 
     [self errorManag:0]; 
    } 

    else 
    { 
     [udpSocket sendData:Content toHost:host port:port withTimeout:1 tag:tag]; 
     NSLog(@"Gestuurd"); 
    } 
} 

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data 
    fromAddress:(NSData *)address 
withFilterContext:(id)filterContext 
{ 
    NSLog(@"niets."); 
    NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
if (msg) 
{ 
     NSLog(@"iets gekregen"); 
} 
else 
{ 
    NSLog(@"Error convertion"); 
    //[self logError:@"Error converting received data into UTF-8 String"]; 
} 
//NSString *test = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
//NSLog(@"%@",test); 
//[udpSocket sendData:data toAddress:address withTimeout:-1 tag:0]; 
    NSLog(@"HMMMM"); 
    messageField.text = [[NSString alloc] initWithFormat:@"RE: %@", msg]; 
} 
+0

*「我的iPhone應用程序可以看/讀它」* - 你的意思是**不能**在那裏? – Jim 2012-04-25 11:48:42

+0

感謝您的幫助:D – Melkon 2012-04-25 12:01:47

+0

您是否嘗試在運行模擬器的Mac上使用代理(如Charles)運行?這幫了我很多次...... – 2012-04-25 12:19:14

回答

2

我發現我寫的viewDidLoad中綁定端口:0,因爲這建議是之前給我。

這使移動設備監聽一個隨機端口而不是端口12345.更改綁定到端口12345並工作!

相關問題