简体   繁体   English

为什么GCDAsyncUdpSocket在广播模式下一段时间后无法发送/接收数据包?

[英]why GCDAsyncUdpSocket cannot send/receive packets after a while in broadcast mode?

I am using GCDAsyncUdpSocket to write a UDP socket in my app. 我正在使用GCDAsyncUdpSocket在我的应用程序中编写UDP套接字。 The scenario is like this: when users click the button, it will send a broadcast packet in LAN then listen to the response, there is a server in LAN which will respond with one UDP packet. 场景是这样的:当用户点击按钮时,它将在LAN中发送广播数据包然后收听响应,LAN中有一个服务器将响应一个UDP数据包。 When the app receives the response, it will do something. 当应用收到响应时,它会执行某些操作。

I set GCDAsyncUdpSocket as followings: 我将GCDAsyncUdpSocket设置如下:

- (void)setupSocket
{
    _udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

    NSError *error = nil;

    if (![_udpSocket bindToPort:18686 error:&error]) {
        NSLog(@"Error binding: %@",error);
        return;
    }

    if (![_udpSocket beginReceiving:&error]) {
        NSLog(@"Error receiving: %@",error);
        return;
    }

    if (![_udpSocket enableBroadcast:YES error:&error]) {
        NSLog(@"Error enableBroadcast: %@",error);
        return;
    } 
}

then i send Packet in button action as following: 然后我按钮按钮动作发送如下:

NSString *host = @"255.255.255.255";
int port = 8585;
NSString *msg = @"Hello from iOS";
NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];
[_udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:0]; 

in

- (void)udpSocket:(GCDAsyncUdpSocket *)sock     didReceiveData:(NSData *)data
                                                fromAddress:(NSData *)address
                                                withFilterContext:(id)filterContext

method i listen the port to do somethings. 方法我听端口做事。 It works perfectly at beginning, but if you try to click the button later (about 1 hour), then it cannot send UDP packet any more. 它在开始时工作正常,但如果您稍后尝试单击该按钮(约1小时),则它不能再发送UDP数据包。

My server in LAN will print the data received. 我在LAN中的服务器将打印收到的数据。 I thought there was something wrong with send method. 我觉得send方法有问题。 so i use BSD socket methods to send The data. 所以我使用BSD套接字方法发送数据。 and use GCDAsyncUdpSocket to receive the response. 并使用GCDAsyncUdpSocket接收响应。 but the same thing happened after a while. 但过了一会儿就发生了同样的事情。 this time i can send but cannot receive. 这次我可以发送但无法接收。

Am i missing something about GCDAsyncUdpSocket ? 我错过了一些关于GCDAsyncUdpSocket吗? why it cannot send/receive after a while? 为什么一段时间后不能发送/接收? Any help would be much appreciated. 任何帮助将非常感激。

It may be some timeout setting. 可能是某些超时设置。 Implement the GCDAsyncUdpSocketDelegate protocol to fetch detailed information about what is going on. 实现GCDAsyncUdpSocketDelegate协议以获取有关正在进行的操作的详细信息。

The hard solution is to establish a new connection. 硬解决方案是建立新连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM