Transfer files between 2 iPhones over wifi? - iphone

I've spent a few days looking for different solutions, but the whole area is quite complicated, and I'm wondering if anybody knows of any project where I can simply transfer NSData or an NSString or some other simple file over wifi to another iPhone on the network?

Np. Use bonjour to search for devices. Then use CocoaAsyncSocket to send and receive data. It works like a charm.
Little info about AsyncSock:
GCDAsyncSocket and AsyncSocket are TCP/IP socket networking libraries.
Here are the key features available in both:
Native objective-c, fully self-contained in one class. No need to muck
around with sockets or streams. This class handles everything for you.
Full delegate support Errors, connections, read completions, write
completions, progress, and disconnections all result in a call to your
delegate method.
Queued non-blocking reads and writes, with optional timeouts. You tell
it what to read or write, and it handles everything for you. Queueing,
buffering, and searching for termination sequences within the stream -
all handled for you automatically.
Automatic socket acceptance. Spin up a server socket, tell it to
accept connections, and it will call you with new instances of itself
for each connection.
Support for TCP streams over IPv4 and IPv6. Automatically connect to
IPv4 or IPv6 hosts. Automatically accept incoming connections over
both IPv4 and IPv6 with a single instance of this class. No more
worrying about multiple sockets.
Support for TLS / SSL Secure your socket with ease using just a single
method call. Available for both client and server sockets.

Related

How to implement multicast sockets in swift?

I'm writing a server that, among other things, needs to be constantly sending data in different multicast addresses. The packages being sent might be received by a client side (an app) which will be switching between the mentioned addresses.
I'm using Perfect (https://github.com/PerfectlySoft/Perfect) for writing the server side, however had no luck using the Perfect-Net module nor using CocoaAsyncSocket. How could i implement both the sender and the receiver using swift? Any could snippet would be really useful.
I've been reading about multicasting and when it comes to the receiver, i've notice that in most languages (i.e. java or c#) the receiver often indicates a port number and a multicast ip-address, but when is the connection with the server being made? When does the socket bind to the real server ip-address?
Thanks in advance
If we talk about the TCP/IP stack, only IP and UDP support broadcasts and multicasts. They're both connectionless, and this is why you see only sending and receiving to special multicast addresses, but no binds and connects. You see it in different languages because (a) protocols are language-agnostic and (b) most implementations put reasonable efforts in trying to be compatible with BSD sockets interface.
If you want that true multicast, you'll need to find a swift implementation of sockets that allow setting options. Usual names for this operation is setsockopt. Multicast sender side doesn't need anything beyond a basic UDP socket (I suggest using UDP, not IP), while sender needs to be added to a multicast group. This Python example pretty much describes it.
However, it's worth noting that routers don't route broadcasts and multicasts. Hence you cannot use it over internet. If you need to use internet in your project, I'd advise you to use TCP - or websockets if your clients are browsers - and send messages to "groups" of them manually.
I guess you actually want Perfect-Kafka or Perfect-Mosquitto - Message Queue which allows a server to publish live streams to the client side subscribers. Low-level sockets will not easily fulfill your requirement.

UDP for multiplayer game

I have no experience with sockets nor multiplayer programming.
I need to code a multiplayer mode for a game I made in c++. It's a puzzle game but the game mode will not be turn-based, it's more like cooperative.
I decided to use UDP, so I've read some tutorials, and all the samples I find decribes how to create a client that sends data and a server that receives it.
My game will be played by two players, and both will send and receive data to/from the other.
Do I need to code a client and a server?
Should I use the same socket to send and receive?
Should I send and receive data in the same port?
Thanks, I'm kind of lost.
Read how the masters did it:
http://www.bluesnews.com/abrash/chap70.shtml
Read the code:
git clone git://quake.git.sourceforge.net/gitroot/quake/quake
Open one UDP socket and use sendto and recvfrom. The following file contains the functions for the network client.
quake/libs/net/nc/net_udp.c
UDP_OpenSocket calls socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)
NET_SendPacket calls sendto
NET_GetPacket calls recvfrom
Do I need to code a client and a server?
It depends. For a two player game, with both computers on the same LAN, or both on the open Internet, you could simply have the two computers send packets to each other directly.
On the other hand, if you want your game to work across the Internet, when one or both players are behind a NAT and/or firewall, then you have the problem that the NAT and/or firewall will probably filter out the other player's incoming UDP packets, unless the local player goes to the trouble of setting up port-forwarding in their firewall... something that many users are not willing (or able) to do. In that case, you might be better off running a public server that both clients can connect to, which forwards data from one client to another. (You might also consider using TCP instead of UDP in that case, at least as a fallback, since TCP streams are in general likely to have fewer issues with firewalls than UDP packets)
Should I use the same socket to send and receive?
Should I send and receive data in the same port?
You don't have to, but you might as well -- there's no downside to using just a single socket and a single port, and it will simplify your code a bit.
Note that this answer is all about using UDP sockets. If you change your mind to use TCP sockets, it will almost all be irrelevant.
Do I need to code a client and a server?
Since you've chosen to to use UDP (a fair choice if your data isn't really important and benefits more from lower latency than reliable communication), you don't have much of a choice here: a "server" is a piece of code for receiving packets from the network, and your "client" is for sending packets into the network. UDP doesn't provide any mechanism for the server to communicate to the client (unlike TCP which establishes a 2 way socket). In this case, if you want to have two way communication between your two hosts, they'll each need server and client code.
Now, you could choose to use UDP broadcasts, where both clients listen and send on the broadcast address (usually 192.168.1.255 for home networks, but it can be anything and is configurable). This is slightly more complex to code for, but it would eliminate the need for client/server configuration and may be seen as more plug 'n play for your users. However, note that this will not work over the Internet.
Alternatively, you can create a hybrid method where hosts are discovered by broadcasting and listening for broadcasts, but then once the hosts are chosen you use host to host unicast sockets. You could provide fallback to manually specify network settings (remote host/port for each) so that it can work over the Internet.
Finally, you could provide a true "server" role that all clients connect to. The server would then know which clients connected to it and would in turn try to connect back to them. This is a server at a higher level, not at the socket level. Both hosts still need to have packet sending (client) and receiving (server) code.
Should I use the same socket to send and receive?
Well, since you're using UDP, you don't really have a choice. UDP doesn't establish any kind of persistent connection that they can communicate back and forth over. See the above point for more details.
Should I send and receive data in the same port?
In light of the above question, your question may be better phrased "should each host listen on the same port?". I think that would certainly make your coding easier, but it doesn't have to. If you don't and you opt for the 3rd option of the first point, you'll need a "connect back to me on this port" datafield in the "client's" first message to the server.

iPhone Native system routines(datagram-socket-type)

Sockets are full-duplex communication
channels between processes either
local to the same host machine or
where one process is on a remote host.
Unlike pipes, in which data goes in
one direction only, sockets allow
processes both to send and receive
data. NSFileHandle facilitates
communication over stream-type sockets
by providing mechanisms run in
background threads that accept socket
connections and read from sockets.
NSFileHandle currently handles only
communication through stream-type
sockets. If you want to use datagrams
or other types of sockets, you must
create and manage the connection using
native system routines.
The process on one end of the
communication channel (the server)
starts by creating and preparing a
socket using system routines. These
routines vary slightly between BSD and
non-BSD systems, but consist of the
same sequence of steps:
Create a stream-type socket of a
certain protocol.
Bind a name to the socket.
Adding itself as an observer of
NSFileHandleConnectionAcceptedNotification.
Sending acceptConnectionInBackgroundAndNotify
to this file handle object.
This method accepts the connection in the
background, creates a new NSFileHandle
object from the new socket descriptor,
and posts an NSFileHandleConnectionAcceptedNotification.
Now I saw Michael answer .
About the differences between “stream-type” socket and a “datagram” socket type
Do you have iPhone implementation example for native system routines(datagram-socket-type)?
Ok first I found what I needed, with CFSocket API which will allow me to implement UDP Synchronization.
CFSocket API
Sockets are the most basic level of network communications. A socket acts in a similar manner to a telephone jack. It allows you to connect to another socket (either locally or over a network) and send data to that socket.
The most common socket abstraction is BSD sockets. CFSocket is an abstraction for BSD sockets. With very little overhead, CFSocket provides almost all the functionality of BSD sockets, and it integrates the socket into a run loop. CFSocket is not limited to stream-based sockets (for example, TCP), it can handle any type of socket.
You could create a CFSocket object from scratch using the CFSocketCreate function, or from a BSD socket using the CFSocketCreateWithNative function. Then, you could create a run-loop source using the function CFSocketCreateRunLoopSource and add it to a run loop with the function CFRunLoopAddSource. This would allow your CFSocket callback function to be run whenever the CFSocket object receives a message.
Regardless I found AsyncSocket API.
CocoaAsyncSocket supports TCP and UDP. The AsyncSocket class is for TCP, and the AsyncUdpSocket class is for UDP. Each class is described below.
AsyncSocket is a TCP/IP socket networking library that wraps CFSocket and CFStream. It offers asynchronous operation, and a native cocoa class complete with delegate support. Here are the key features:
Queued non-blocking reads and writes, with optional timeouts. You tell it what to read or write, and it will call you when it's done.
Automatic socket acceptance. If you tell it to accept connections, it will call you with new instances of itself for each connection. You can, of course, disconnect them immediately.
Delegate support. Errors, connections, accepts, read completions, write completions, progress, and disconnections all result in a call to your delegate method.
Run-loop based, not thread based. Although you can use it on main or worker threads, you don't have to. It calls the delegate methods asynchronously using NSRunLoop. The delegate methods include a socket parameter, allowing you to distinguish between many instances.
Self-contained in one class. You don't need to muck around with streams or sockets. The class handles all of that.
Support for TCP streams over IPv4 and IPv6.
The library is public domain, originally written by Dustin Voss. Now available in a public setting to allow and encourage its continued support.
AsyncUdpSocket is a UDP/IP socket networking library that wraps CFSocket. It works almost exactly like the TCP version, but is designed specifically for UDP. This includes queued non-blocking send/receive operations, full delegate support, run-loop based, self-contained class, and support for IPv4 and IPv6.
CocoaAsyncSocket
And here is the CFSocket Reference
CFSocket Reference

Understanding socket basics

I've been reading up on basic network programming, but am having a difficult time finding a straight-forward explanation for what exactly and socket is, and how it relates to either the OSI or TCP/IP stack.
Can someone explain to me what a socket is? Is it a programmer- or API-defined data structure, or is it a hardware device on a network card?
What layers of the mentioned network models deal with "raw" sockets? Transport layer? Network layer?
In terms of the data they pass between them, are socket text-based or binary?
Is there an alternative to sockets-based network programming? Or do all networked applications use some form of socket?
If I can get this much I should have a pretty clear understanding of everything else I'm reading. Thanks for any help!
Short answers:
Socket is an abstraction of an IP connection endpoint - so if you think of it as an API structure, you are not very far off. Please do read http://en.wikipedia.org/wiki/Internet_socket
Internet layer i.e. IP Protocol. In practice you usually use explicitly sockets that bind to a certain transport layer parameters (datagram/UDP or stream/TCP)
Sockets send data, in network byte order - whether it is text or binary, depends on the upper layer protocol.
Theoretically, probably yes - but in practice all IP traffic is done using 'sockets'
Socket is a software mechanism provided by the operating system. Like its name implies, you can think of it like an "electrical outlet" or some electrical connector, even though socket is not a physical device, but a software mechanism. In real world when you have two electrical connectors, you can connect them with a wire. In the same way in network programming you can create one socket on one computer and another socket on another computer and then connect those sockets. And when you write data to one of them, you receive it on the other one. There are also a few different kinds of sockets. For example if you are programming a server software, you want to have a listening socket which never sends or receives actual data but only listens for and accepts incoming connections and creates a new socket for each new connection.
A socket, in C parlance, is a data structure in kernel space, corresponding to one end-point of a UDP or TCP session (I am using session very loosely when talking about UDP). It's normally associated with one single port number on the local side and seldom more than one "well-known" number on either side of the session.
A "raw socket" is an end-point on, more or less, the physical transport. They're seldom used in applications programming, but sometimes used for various diagnostic things (traceroute, ping, possibly others) and may required elevated privileges to open.
Sockets are, in their nature, a binary octet-transport. It is not uncommon to treat sockets (TCP sockets, at least) as being text-based streams.
I have not yet seen a programming model that doesn't involve something like sockets, if you dig deep enough, but there have certainly been other models of doing networking. The "/net/" pseudo-filesystem, where opening "/net/127.0.0.0.1/tcp/80" (or "tcp/www") would give you a file handle where writes end up on a web server on localhost is but one.
Suppose your PC at home, and you have two browser windows open.
One looking at the facebook website, and the other at the Yahoo website.
The connection to facebook would be:
Your PC – IP1+port 30200 ——– facebook IP2 +port 80 (standard port)
The combination IP1+30200 = the socket on the client computer and IP2 + port 80 = destination socket on the facebook server.
The connection to Yahoo would be:
your PC – IP1+port 60401 ——–Yahoo IP3 +port 80 (standard port)
The combination IP1+60401 = the socket on the client computer andIP3 + port 80 = destination socket on the Yahoo server.

How to listen on a network port in Objective-C

I am trying to make an application for iPhone that can listen for traffick on a specific network port.
A server on my network is sending out messages (different status messages for devices the server handles) on a specific port.
My problem is that when I make a thread and makePairWithSocket I block the port for others who want to send messages to the server, so I only want to listen to the traffic on a specifyed port and then check for specific heraders and then use those messages.
I know how to make the connection and talk to the server using write and read streams, but then I makePairWithSocket and block the port for all other devices on the network
Any one that has any suggestions on how to listen on a port in Objective-C without pairing with the server?
Thanks in advance
Daniel
Check out CocoaAsyncSocket. It gives you a nice and structured way (with delegates) to send and receive data... also with multiple clients. The documentation is quite good. project link
edit: Have a look at the AsyncUdpSocket class for a stateless UDP connection.
I think this requires network support well below the socket API level, perhaps at the hardware driver level, assuming the packets are even being routed to your device.