This is based on using the AsyncUdpSocket library.

If you don’t use git you’ll have to download a git client to get the library files.

Add Framework To Your Project

Select the project at the top of the left navigator panel, select the target and then select the Build Phases tab. In the Link Binary with Libraries section click the ‘+’ button and then select the CFNetowrk.framework entry.

The application can now use the classes and functions provided by the framework.  You just need to import the relevant header file where the framework is used, e.g.:

#import <CFNetwork/CFNetwork.h>

Add UDP To Your Project

Add the AsyncUdpSocket.h and AsyncUdpSocket.m files to your project.

In Your .h file

#import "AsyncUdpSocket.h"

@interface MyClass : NSObject
{		//AsyncUdpSocketDelegate not needed

	AsyncUdpSocket *UdpSocket1;
In Your .m file

		//----- CREATE UDP SOCKET -----
		NSLog(@"Creating UDP socket");
		UdpSocket1 = [[AsyncUdpSocket alloc] initWithDelegate:self];
		if (![UdpSocket1 bindToPort:21369 error:nil])
			NSLog(@"Bind error");
		[UdpSocket1 receiveWithTimeout:-1 tag:1];			//Setup to receive next UDP packet

//*********************************
//*********************************
//********** UDP RECEIVE **********
//*********************************
//*********************************
-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data
		   withTag:(long)tag
		  fromHost:(NSString *)host
			  port:(UInt16)port
{
	NSLog(@"Received UDP Packet");

	UInt8 *bytes = (UInt8 *)data.bytes;
	if (data.length >= 4)
		NSLog(@"Byte0: %d, Byte1: %d, Byte2: %d, Byte3: %d", bytes[0], bytes[1], bytes[2], bytes[3]);

	//TX RESPONSE
	UInt8 TxDataBytes[10];
	int TxDataIndex = 0;
				
	TxDataBytes[TxDataIndex++] = 0x01;
	TxDataBytes[TxDataIndex++] = 0x02;
	TxDataBytes[TxDataIndex++] = 0x03;
	TxDataBytes[TxDataIndex++] = 0x04;

	NSData *TxData = [NSData dataWithBytes:&TxDataBytes length:TxDataIndex];
				
	[UdpSocket1 sendData:TxData
				  toHost:host
					port:1234
			 withTimeout:2.0		//Seconds
					 tag:0];


	[UdpSocket1 receiveWithTimeout:-1 tag:1];			//Setup to receive next UDP packet
	return YES;			//Signal that we didn't ignore the packet.
}

Comments