Little problem with AsyncUdpSocket receiving data after connecting to broadcast instead of server

前端 未结 4 1146
天命终不由人
天命终不由人 2021-02-15 22:58

I have a problem with AsyncUdpSocket.

I used to connect to a server, send some data and get some response. Now since I do not know the actual address of the server I had

4条回答
  •  广开言路
    2021-02-15 23:34

    Based on Arthur's answer, here's the working code. I'm wondering if receive should start before the send, just to make sure we don't miss a very fast reply before receive is ready, but so far it doesn't seem necessary in my situation. Also, reference this post on how to create receiving methods.

    AsyncUdpSocket *udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
    [udpSocket bindToPort:1234 error:nil ];
    [udpSocket enableBroadcast:YES error:nil];
    
    NSData* data=[messageToSend dataUsingEncoding:NSUTF8StringEncoding];
    
    if ([udpSocket sendData:data toHost:@"255.255.255.255" port:4321 withTimeout:3 tag:0])
    {
        //2 second timeout. onUdpSocket methods will provide results
        [udpSocket receiveWithTimeout:2 tag:0];
    }
    

提交回复
热议问题