Peer To Peer Poker App

I wish to build a simple peer-peer app using Sockets. A accepts a number and sends it to B. Then B returns the square of the number back to A. A sends to B on port 6000 and B sends back to A on port 8000. So both the machines act as clients when they must send, and as servers when they must receive.

OS X and iOS provide four APIs for discovering and advertising network services:

  • NSNetService—A high-level Objective-C API suitable for most app developers.

  • CFNetService—A high-level C API suitable for use in Core Foundation code.

  • DNS Service Discovery—A low-level C API suitable for cross-platform code. This API also offers more flexibility than the higher-level APIs.

  • Game Kit framework—A high-level Objective-C API that provides peer-to-peer communication support for games, both locally (using infrastructure Wi-Fi and Bluetooth) and globally over the Internet.

In addition to these APIs, the Multipeer Connectivity Framework provides support for discovering and communicating with instances of your app and related apps on nearby devices using infrastructure Wi-Fi, peer-to-peer Wi-Fi, and either Bluetooth (for iOS) or Ethernet (for OS X).

As a rule, you should use Game Kit only for game-related peer-to-peer networking. For other peer-to-peer networking between iOS devices running iOS 7 and later, you should consider using the Multipeer Connectivity framework.

For compatibility with older versions of iOS, you can also write your own networking code and use CFNetService or NSNetService to advertise its availability.

Note: On devices that support Bluetooth, Bluetooth communication is automatically used by Game Kit. (Bonjour over Bluetooth can also be enabled when using the DNS Service Discovery C API by setting the interfaceIndex to kDNSServiceFlagsIncludeP2P. See Bonjour over Bluetooth on iOS 5 and Later for details.)

Bonjour Service Overview

A Bonjour service advertisement consists of three parts:

  • Service name—This name must be unique to a particular instance of your program running on a particular computer.

  • Service type—This must be the same for all instances of your program, and should be registered with the Internet Assigned Numbers Authority (IANA).

  • Domain—If the domain value is empty, the host chooses the appropriate domains in which to publish or browse.

When an app browses for Bonjour services, it asks for services matching a particular type in a particular domain, and it gets back a list of matching service names. It should then present an appropriate UI to the user. When the user tells the app to connect to a particular service, the app should then connect to the service using a connect-to-service API. (If this is not possible for some reason, the app can pass the service’s hostname and port to a connect-by-name API or, if a connect-by-name API is not available, the app can ask Bonjour to resolve the hostname, and the app can then connect by IP address and port number.)

Publishing a Network Service

Bonjour zero-configuration networking lets you advertise network services, such as a printer or a document syncing service, on a network. There are three ways to publish a network service:

  • For Objective-C and Core Foundation code, the recommended way is with the CFNetServices API.

  • For portable C code that must run on operating systems other than iOS and OS X, the DNS Service Discovery C API is recommended.

You can publish a network service with the following steps:

  1. Create a socket to listen for connections to the service. See Writing a TCP-Based Server in Networking Programming Topics for the recommended way to listen for connections on a network socket.

  2. Create a service object, providing the port of your socket, the domain (usually an empty string), and the service type string of your choosing:

    • With Foundation, initialize an NSNetService object with the initWithDomain:type:name:port: method.

    • With Core Foundation, create a CFNetServiceRef object with the CFNetServiceCreate function.

    • With the DNS Service Discovery API, call DNSServiceRegister to return a DNSServiceRef object.

  3. Assign a delegate or callback:

    • With Foundation, assign a delegate to the NSNetService object with the delegate method.

    • With Core Foundation, assign a client callback to the CFNetServiceRef object with the CFNetServiceSetClient function.

    • With the DNS Service Discovery API, you should pass a client callback (and, optionally, a pointer to a context object of your choosing) in your call to DNSServiceRegister. At this point, you are done except for handling callbacks when they occur.

  4. Schedule or reschedule the service, if necessary:

    • With Foundation, the service is automatically scheduled on the current run loop in the default mode. If you need to schedule the object on another run loop or in a different mode, you should unschedule it and reschedule it at this point.

    • With Core Foundation, you must schedule the CFNetServicesRef object on a run loop by calling CFNetServiceScheduleWithRunLoop.

    • With the DNS Service Discovery API, call DNSServiceSetDispatchQueue to schedule the service on a dispatch queue. (If you must support an OS prior to OS X v10.7, see the SRVResolver sample code project for an example of how to use DNS Service Discovery without Grand Central Dispatch.)

  5. Publish the service, if necessary:

    • With Foundation, publish the service by calling the publish method.

    • With Core Foundation, publish the service by calling CFNetServiceRegisterWithOptions.

    • With the DNS Service Discovery API, no further action is necessary; the service was already published when you called DNSServiceRegister.

After your service is published, you can listen for connections on your socket and set up input and output streams when a connection is made.

Important: If you create a custom protocol, you should use a custom service type, and register that service type with IANA. For details, see RFC 6335.

Browsing for and Connecting to a Network Service

The process for finding and resolving a network service is as simple as the process for publishing one. To browse for network services in Objective-C, create an instance of the NSNetServiceBrowser class and assign it a delegate. Then, call the searchForServicesOfType:inDomain: method on the service browser. The netServiceBrowser:didFindService:moreComing: delegate method is called once for every service found.

To connect to a service, first stop the browsing by calling stop (unless you have a specific reason to keep browsing), then call the getInputStream:outputStream: method on the NSNetService object that represents the service. The address of the service is resolved automatically.

You can also use the CFStreamCreatePairWithSocketToNetService function with a CFNetServiceRef object to connect to a Bonjour service.

Important: If you are using ARC, you should read NSNetService and Automatic Reference Counting (ARC).

Resolving a Network Service

You may need to resolve a network service manually to provide the service’s address to an API that does not accept network service names. To resolve a network service in Objective-C, first stop the browsing by calling stop (unless you have a specific reason to keep browsing), then call the resolveWithTimeout: method on the NSNetService object that represents the service.

The netServiceDidResolveAddress: method is called on the service’s delegate when the service’s address has been resolved. You can then access the service’s hostname with the hostName method or its address information with the addresses method. To avoid unnecessary network traffic, you should also call stop on the NSNetService object as soon as it returns a set of addresses.

Important: The resolution process returns both numerical IP addresses and a hostname. The IP addresses can be an arbitrary mix of IPv4 and IPv6 addresses. Unless you are doing something unusual, you should normally pass the hostname to any API that supports hostnames rather than using the IP addresses directly, because otherwise you would otherwise have to write your own code to try connecting to each of the multiple IP addresses in parallel or in series (described further in Avoid Resolving DNS Names Before Connecting to a Host).

The resolver caches the mapping from hostname to IP addresses, so future lookups do not result in any additional network traffic.

Multipeer Connectivity Overview

The Multipeer Connectivity Framework provides a layer on top of Bonjour that lets you communicate with apps running on nearby devices (over infrastructure Wi-Fi, peer-to-peer Wi-Fi, and either Bluetooth (for iOS) or Ethernet (for OS X) without having to write lots of networking code specific to your app.

With Multipeer Connectivity, your app advertises its availability. It can then discover other instances of your app (or other apps that share the same service type) running on nearby devices, and can invite those nearby peers to join a session. If they accept the invitation, your app can send messages and files to one or more of the connected peers with just a single method call.

Important: As with Bonjour, your app must provide a service type, and you should register that service type with IANA. For details, see RFC 6335.

If you need stream-based communication, your app can open a unidirectional stream to any connected peer (which can also open a unidirectional stream back to your app in response).

Finally, Multipeer Connectivity provides the ability to share small amounts of data (such as the user’s screen name) outside the context of a session, if desired, allowing you to provide the user with information that they can use when choosing peers to invite into a session.

To Learn More

Multipeer Connectivity—Read Multipeer Connectivity Framework Reference and the MultipeerGroupChat sample code project.

Game Kit—Read Game Center Programming Guide, Game Kit Framework Reference, and the GKRocket and GKTank sample code projects.

NSNetService—Read NSNetServices and CFNetServices Programming Guide, NSNetServiceBrowser Class Reference, NSNetServiceBrowserDelegate Protocol Reference, and NSNetServiceDelegate Protocol Reference. For sample code, see the RemoteCurrency sample code project.

CFNetService—Read NSNetServices and CFNetServices Programming Guide and CFNetServices Reference.

DNS Service Discovery—Read DNS Service Discovery Programming Guide and DNS Service Discovery C Reference.



Copyright © 2004, 2017 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2017-03-27

Support peer-to-peer connectivity and the discovery of nearby devices.

SDKs

  • iOS 7.0+
  • macOS 10.10+
  • Mac Catalyst 13.0+
  • tvOS 10.0+

Overview

The Multipeer Connectivity framework supports the discovery of services provided by nearby devices and supports communicating with those services through message-based data, streaming data, and resources (such as files). In iOS, the framework uses infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks for the underlying transport. In macOS and tvOS, it uses infrastructure Wi-Fi, peer-to-peer Wi-Fi, and Ethernet.

Architecture

When working with the Multipeer Connectivity framework, your app must interact with several types of objects:

  • Session objects (MCSession) support communication between connected peer devices. Your app creates a session and adds peers to it when peers accept an invitation to connect, and it creates a session when invited to connect by another peer. Session objects maintain a set of peer ID objects that represent the peers connected to the session.

  • Advertiser objects (MCNearbyServiceAdvertiser) tell nearby peers that your app is willing to join sessions of a specified type. An advertiser object uses a single local peer object to provide information that identifies the device and its user to other nearby devices.

  • Advertiser assistant objects (MCAdvertiserAssistant) provide the same functionality as advertiser objects, but also provide a standard user interface that allows the user to accept invitations. If you wish to provide your own user interface, or if you wish to exercise additional programmatic control over which invitations are displayed, use an advertiser object directly.

  • Browser objects (MCNearbyServiceBrowser) let your app search programmatically for nearby devices with apps that support sessions of a particular type.

  • Browser view controller objects (MCBrowserViewController) provide a standard user interface that allows the user to choose nearby peers to add to a session.

  • Peer IDs (MCPeerID) uniquely identify an app running on a device to nearby peers.

Discovery Phase and Session Phase

Peer To Peer Payment

This framework is used in two phases: the discovery phase and the session phase.

In the discovery phase, your app uses an MCNearbyServiceBrowser object to browse for nearby peers, optionally using the MCBrowserViewController object to display a user interface.

The app also uses an MCNearbyServiceAdvertiser object or an MCAdvertiserAssistant object to tell nearby peers that it is available, so that apps on other nearby devices can invite it to a session.

During the discovery phase, your app has limited communication with and knowledge of other peers; it has access to the discoveryInfo data that other nearby clients provide, and any context data that other peers provide when inviting it to join a session.

After the user chooses which peers to add to a session, the app invites those peers to join the session. Apps running on the nearby devices can choose whether to accept or reject the invitation, and can ask their users for permission.

Peer to peer payment

Peer To Peer Music Sharing

If the peer accepts the invitation, the browser establishes a connection with the advertiser and the session phase begins. In this phase, your app can perform direct communication to one or more peers within the session. The framework notifies your app through delegate callbacks when peers join the session and when they leave the session.

If the app moves into the background, the framework stops advertising and browsing and disconnects any open sessions. Upon returning to the foreground, the framework automatically resumes advertising and browsing, but the developer must reestablish any closed sessions.

Topics

class MCAdvertiserAssistant

The MCAdvertiserAssistant is a convenience class that handles advertising, presents incoming invitations to the user, and handles users’ responses. Use this class to provide a user interface for handling invitations when your app does not require programmatic control over the invitation process.

class MCBrowserViewController

The MCBrowserViewController class presents nearby devices to the user and enables the user to invite nearby devices to a session. To use this class in iOS or tvOS, call methods from the underlying UIViewController class (prepare(for:sender:) and performSegue(withIdentifier:sender:) for storyboards or present(_:animated:completion:) and dismiss(animated:completion:) for nib-based views) to present and dismiss the view controller. In macOS, use the comparable NSViewController methods presentAsSheet(_:) and dismiss(_:) instead.

class MCNearbyServiceAdvertiser

The MCNearbyServiceAdvertiser class publishes an advertisement for a specific service that your app provides through the Multipeer Connectivity framework and notifies its delegate about invitations from nearby peers.

class MCNearbyServiceBrowser

Searches (by service type) for services offered by nearby devices using infrastructure Wi-Fi, peer-to-peer Wi-Fi, and Bluetooth (in iOS) or Ethernet (in macOS and tvOS), and provides the ability to easily invite those devices to a Multipeer Connectivity session (MCSession).

class MCPeerID

An MCPeerID object represents a peer in a multipeer session.

class MCSession

An MCSession object enables and manages communication among all peers in a Multipeer Connectivity session.

protocol MCAdvertiserAssistantDelegate

The MCAdvertiserAssistantDelegate protocol describes the methods that the delegate object for an MCAdvertiserAssistant instance can implement to handle advertising-related events.

protocol MCBrowserViewControllerDelegate

The MCBrowserViewControllerDelegate protocol defines the methods that your delegate object can implement to handle events related to the MCBrowserViewController class.

protocol MCNearbyServiceAdvertiserDelegate

Peer To Peer Applications

The MCNearbyServiceAdvertiserDelegate protocol describes the methods that the delegate object for an MCNearbyServiceAdvertiser instance can implement for handling events from the MCNearbyServiceAdvertiser class.

protocol MCNearbyServiceBrowserDelegate

Ios Peer To Peer

The MCNearbyServiceBrowserDelegate protocol defines methods that a MCNearbyServiceBrowser object’s delegate can implement to handle browser-related events.

protocol MCSessionDelegate

The MCSessionDelegate protocol defines methods that a delegate of the MCSession class can implement to handle session-related events. For more information, see MCSession.

Comments are closed.