CocoaAsyncTask can't connect real device
-
03-06-2021 - |
Question
I'm using CocoaAsyncTask and trying to connect to the localhost. When I run it from the simulator, it works (I'm checking it with the provided echo server) but when I run it on the actual device, nothing happens.. the code is:
if(![socket connectToHost:@"localhost" onPort:8080 error:nil]) {
NSLog(@"Error..");
}
-(void)socket:(GCDAsyncSocket *)socket didConnectToHost:(NSString *)host: port:(uint16_t)port {
NSLog(@"Connected");
}
Any ideas? Thanks!
Solution
You are providing the address as being "localhost" whilst you attempt to connect to a server that is not locally installed (local = on the exact same host and interface). See the wikipedia entry on "localhost".
It works from the simulator as that one uses your Mac's networking interface, hence "localhost" refers to the machine you run the server from as well as the client.
You will need to provide the local IP address of your hosting machine (e.g. your Mac). Usually that is something like 192.168.1.100 or 192.168.0.100 - but to be more precise on that stuff;
192.168.xxx.xxx = class C non-routable addresses
10.xxx.xxx.xxx = class A non-routable addresses
Whereas xxx stands for any value between 0 and 255.
To find out about your local IP-address, use the System Preferences -> Network Panel. Check the value below Status for "...the IP address xxx.xxx.xxx.xxx"