从 iOS 应用程序上的 UDP 服务器接收数据无法在 Linux 服务器上工作,但可以在 macbook pro 上工作 [关闭]

2024-02-15

背景: 我做了一个基于UDP的IPhone套接字应用程序。它在与 Linux [Ubuntu] 服务器通信时充当客户端和服务器。 我使用 GCDAsyncUdpSocket 来发送和接收数据。我的 Macbook 上还有一个备份服务器/客户端应用程序,用于测试/验证套接字通信应用程序。它的作用就像 Linux [Ubuntu] 服务器。它工作完美。

问题:我无法从 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]; 
}

我发现我在ViewDidLoad中写了绑定到端口:0,因为这个建议之前已经给过我了。

这导致移动设备侦听随机端口而不是端口 12345。将绑定更改为端口 12345 并且有效!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 iOS 应用程序上的 UDP 服务器接收数据无法在 Linux 服务器上工作,但可以在 macbook pro 上工作 [关闭] 的相关文章

随机推荐