I’ve been trying for days now to try and sort this out. Today was another day full of trying things, having my latest attempt just end in failure. Rather than just close it and go off to bed thinking ‘Another day gone of just failing to do this 1 thing.’, I thought i’d ask on here. I’m at my wits end now. CocoaAsyncSocket I can’t get to work, nor do any tutorials or other ‘solutions’ that i’ve found. This is what i want to do:
The user selects from a list a computer or iphone on the wifi network to connect to, which also has the app running. They connect, another button is pressed and data is sent from the first device to the second. The second device can also send things back. It’s a peer to peer network.
Amy help anybody can give me is appreciated. I really just need a simple way to do this, because it’s beginning to not be worth it for the amount it’d be used versus how long it’s taking to implement. But i don’t want to just give up on something like this where I’ve seen the finishing line on numerous occasions but haven’t been able to get past the numerous hurdles.
There are really three parts to your question:
On the low level you can transfer data using a TCP/IP connection (you listen on some port of host A and connect to that host from the host B). However, host B needs to find out about the fact that host A is on the same local network – this is typically done by host A sending broadcast messages (let’s say via UDP) on the local network that identify it so host B can determine the IP address of A so it can connect to it. And finally, on the non-Mac device you may want to start all this only once you detect that the device is on a WiFi network, since it won’t work otherwise.
Implementing all of the above (except for the data transfer) is not quite trivial, but fortunately Apple provides several tools for this:
SCNetworkReachabilityprovides an API that will notify you when the device has joined a Wifi network (iOS only, not needed on Mac OS X). Then service advertizing and discovery can be implemented using Bonjour: you register your own service usingNSNetServiceon one host and the other can callNSNetServiceBrowserto browse the local network for available peers. Finally, you can use streams to transfer the data once you have discovered the desired service. Have a look at the Apple documentation – there is sample code for all the mentioned facilities. I wouldn’t call is simple, but that’s because what you want is technically not quite simple ;).