I am new to objective C and I need to send a simple message via UDP. The server part is working cause it is implemented in C#.
The server code in C# is:
var server = new UdpClient(8585);
var groupEP = new IPEndPoint(IPAddress.Parse("192.168.0.120"),8585);
byte[] bytes = server.Receive(ref groupEP);
and the client part in c# is:
System.Net.Sockets.UdpClient client;
client = new System.Net.Sockets.UdpClient("192.168.0.120",8585);
client.Send(new byte[]{1,2,3,4},4);
how can I do the same client part in objective c? I know there are a lot of tutorials on the internet such as this library. when I import that library to my project I do not know how to instantiate a new object. I have tried:
[[GCDAsyncUdpSocket alloc] initWithSocketQueue:... ??? I don't know how to initialize it.
I will appreciate if someone can show me a simple example of how could I replicate the client part into objective c.
download GCDAsyncUdpSocket from here. then you may send packets as:
GCDAsyncUdpSocket *udpSocket ; // create this first part as a global variable
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSData *data = [
[NSString stringWithFormat:@"%Hello Wold"
dataUsingEncoding:NSUTF8StringEncoding
];
[udpSocket sendData:data toHost:@"192.168.10.111" port:550 withTimeout:-1 tag:1];
Apple provides a sample project called UDPEcho. Although it's a Mac project, it relies mainly on classes from Core Foundation which is also available on iOS and the lessons it contains should apply equally well to iOS.
First, have a read of this article which outlines some of the fundamental types of network communication available in iOS.
In particular, Apple have an example of network communication using sockets and the NSStream
class here.
You can use the normal BSD socket API but it is discouraged because they don't work with certain iOS network features like VPN on-demand. If this is of no consequence then you can check here for examples of how to use sockets in C.
From personal experience, it's not as easy as what you've got in C#.
I manage to solve the problem using monotouch. I just do it the same way I will do it in c#:
System.Net.Sockets.UdpClient client;
client = new System.Net.Sockets.UdpClient("192.168.0.120",550);
client.Send(new byte[]{1,2,3,4},4);
I don't want to pay for the license though. it will cost $400. If I where to have more than 3 lines of code I might have think of it.