0

I am trying to create a UDP socket and send data to a broadcasting port so that I can receive the same on other devices in the same WiFi network. I am calculating the IP address of broadcasting port as given in the accepted answer here.

After that I have written some connection code which is as below:

self.udpSocket = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue() socketQueue:nil];
NSError *error;
[self.udpSocket enableReusePort:YES error:&error];
[self.udpSocket enableBroadcast:YES error:&error];

- (IBAction)sendMessageToBroadcastPort:(id)sender {
 [self.udpSocket sendData:[@"Hi" dataUsingEncoding:NSUTF8StringEncoding] toHost:[self getUDPBroadcastAddress] port:5556 withTimeout:-1 tag:1];
}

I get success in sending the data as the delegate method didSendData: gets called.

Please guide me on what am I missing here.

Thanks!

UPDATE: Cpde for receiving the data from the broadcasting port:

- (void)listenForPackets
{
dispatch_queue_t dQueue = dispatch_queue_create("client udp socket", NULL);
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dQueue socketQueue:nil];
NSError *error = nil;

if (![udpSocket bindToPort:5556 error:&error]) {
    NSLog(@"Error binding: %@",error);//not connecting to host
    return;
}
if (![udpSocket beginReceiving:&error]) {
    NSLog(@"Error receiving: %@",error);
    return;
}
NSLog(@"Socket Ready");
}

 - (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
  fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (msg)
{
    NSLog(@"RCV: %@", msg);
}
else
{
    NSString *host = nil;
    uint16_t port = 0;
    [GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];
    NSLog(@"Unknown message from : %@:%hu", host, port);
}
}

The broadcasting IP which I get after calculation is 192.168.2.255

UPDATE 2::

The scenario I am facing is really different and weird. The receiving works sometimes and sometimes it doesn't. When I installed two apps there were no data received. Only sending was successful. I kept the apps on and after some time the app started receiving data. At some instances it stopped receiving after some time or kept receiving without any issue. What can be the issue?

Community
  • 1
  • 1
Yogi
  • 3,578
  • 3
  • 35
  • 56
  • 1
    You don't need to call `connectToHost` as UDP is connection less. You should use `sendData:toHost:port:withTimeout` – Paulw11 Jun 01 '16 at 05:14
  • Hey @Paulw11, your suggestion made my day! Also This is very IMPORTANT: When you are only receiving, please don't write socket.connect(toHost:IP, onPort: PORT). Only socket.bind(toPort: PORT) would do start the receiving. Thanks :) – iHarshil Feb 25 '20 at 14:11

2 Answers2

1

Try like Below :

Create a Socket :

-(void)createClientUdpSocket
{
    dispatch_queue_t dQueue = dispatch_queue_create("client udp socket", NULL);

    sendUdpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue: dQueue socketQueue: nil];
    [sendUdpSocket receiveOnce:nil];
    [sendUdpSocket joinMulticastGroup:[self getIPAddress] error:nil]; // Put your IP Address
    NSLog(@"Ready");
}

Delegate method for Socket.

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
{
     NSString *ip = [GCDAsyncUdpSocket hostFromAddress:address];
     uint16_t port = [GCDAsyncUdpSocket portFromAddress:address];
     NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
     // Continue to wait for a message to receive the next
     NSLog (@ "The server receives the response [%@:% d]%@", ip, port, s);
     [sock receiveOnce:nil];

     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
     [self sendBackToHost:ip port:port withMessage:s];
   });
}

-(void)sendBackToHost:(NSString *)ip port:(uint16_t)port withMessage:(NSString *)s{

      [sendUdpSocket sendData:yourData toHost:yourIP port:5556 withTimeout:60 tag:200];
       NSLog(@"sent message to server");
}

Hope this will help. Its working for me :)

Soumya Ranjan
  • 4,817
  • 2
  • 26
  • 51
  • Thanks for your response. Now as I am not connecting the socket, so I am not getting the error but the sample receiver app isn't receiving anything when I try to read the contents of broadcasting IP. I have updated my question with receiver's code. Or is there any issue with my calculated IP? Please guide. – Yogi Jun 01 '16 at 05:49
  • I have updated my question based on what I could manage to do till now. Please have a look. – Yogi Jun 02 '16 at 05:23
  • Now receiving works but with an issue. Please check my updated question. – Yogi Jun 03 '16 at 05:00
  • I have implemented these code but didReceive data method call and i got ip address but stream did connect method not called or any other delgate method not call pls reply ASAP – DURGESH Feb 20 '17 at 05:27
0

I am answering this question as the scenario I faced is really different and weird. The receiving works sometimes and sometimes it doesn't. When I installed two apps there were no data received. Only sending was successful. I kept the apps on and after some time the app started receiving data. At some instances it stopped receiving after some time.

Actually I was using a shared internet connection of my mac which is connected to ethernet. I changed my WiFi network to a proper broadband network and since then it works without any issue.

Hope this helps someone with similar scenario :)

Yogi
  • 3,578
  • 3
  • 35
  • 56