简体   繁体   中英

iOS UDP communication both ways

I'm making an iOS application that is supposed to communicate using the UDP protocol (the devices are connected to the same Wi-Fi network). I managed to create a socket, and send some data to the designated IP address:

const char *ip = "192.168.1.100";

- (void)initNetworkCommunication {

    cfSocket = CFSocketCreate(kCFAllocatorDefault, AF_INET, SOCK_DGRAM, IPPROTO_UDP, 0, NULL, NULL);

    if ( cfSocket == NULL) {
        NSLog(@"CfSocketCreate failed");
    }else{
        if( cfSocket ) {
            NSLog(@"Socket created ");

            struct sockaddr_in addr;
            memset(&addr, 0, sizeof(addr));
            addr.sin_len = sizeof(addr);
            addr.sin_family = AF_INET;
            addr.sin_port = htons(1470); //port
            inet_pton(AF_INET,ip, &addr.sin_addr); //ip adress

            CFDataRef addrData = CFDataCreate(NULL, (const UInt8*)&addr, sizeof(addr));
            CFSocketSetAddress (cfSocket, addrData);
            char message []= "UDP test message";

            CFDataRef Data = CFDataCreate(NULL, (const UInt8*)message, sizeof(message));
            CFSocketSendData(cfSocket,addrData, Data, 0);
        }
    }

This works quite well i think, as the device gets the message. The problem is I really have no idea where to start on listening for/receiving data. I've tried to search for some help, but sadly without any useful results. Most people are using external libraries, which i would like to avoid. If anyone could give me some guidance in this topic, I'd be really thankful.

I have searched some more this morning, and actually found what i was looking for in this topic:

UDP broadcast using CFSocket on IOS

Adding a callback to the socket, together with configuring a RunLoop works like a charm :) And if you want to get the data from the callback just use something like this:

NSData * someData = (NSData*)data;
NSString * someString = [[NSString alloc] initWithData:someData encoding:NSASCIIStringEncoding];

Hope this helps someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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