Re: Understanding NSNetService and peer-to-peer streaming


On Aug 16, 2017, at 9:24 PM, Graham Cox <graham@...> wrote:

So far, so good. But now I need to return data to the ‘server’ peer. The problem is, I don’t know which stream I need to use to do that. When the ‘server’ accepts a connection, it is handed two streams, which are presumably the ones to use. The problem I have is that these streams are just naked streams - there is no associated information that will tell me which ‘client’ they are connected to.

Right. You need to keep track of that yourself, like with a Peer class that can hold onto those streams and act as their delegate.

I have the idea that what I should do is to wrap the stream pair in another object so I can keep them separate, but that still leaves the problem of identifying that object as being a particular server. I can send that identifying information over the stream the first time I use it, and the ‘client’ can then add that information to the server object, but that seems like a kludge - it is relying on my private protocol to pass information that should already be known to the basic NSNetService infrastructure.

NSNetService doesn't really have anything to do with those streams. All Bonjour does is service discovery: it can advertise a service you're running on some port, and it can find other services of a given type. When it resolves a service it gets the IP address and port number. But that's all Bonjour does.

When you ask an NSNetService to open a connection, it just resolves the service and then calls an NSStream factory method to open a TCP socket to that IP address / port. Then it returns you the resulting streams. Its job is done. This is just a convenience method that was added later on to simplify connecting to services.

Once you've opened the streams, you can remember the name of the service that you got them from. Or you can have a protocol that sends the peer name or UUID or whatever over the socket when it opens; it's up to you.


PS: What you're implementing sounds exactly like what the Multipeer Connectivity framework does. Are you aware of it? You could probably save yourself a ton of work by using it.

Join to automatically receive all group messages.