Home > Articles > Operating Systems, Server > Microsoft Windows Desktop

  • Print
  • + Share This
This chapter is from the book

Proximity (Near Field Communications)

Near Field Communications (NFC6) is a set of standards based on Radio-Frequency Identification (RFID) standards for smartphones, tablets, smart tags, and other devices to establish communications in extremely close situations (less than a few inches difference). Two main NFC scenarios exist. The first is a tap gesture for a short transmission of information, such as contact information, a URL, or a “smart poster.” The second is a similar gesture used to create a handshake between two devices so they can establish a peer-to-peer connection over wireless to exchange large amounts of information.

NFC not only operates over extremely short distances, but it also has a fairly slow transfer rate, with theoretical speeds between 50 and 100 bytes per second. For this reason, it is useful for exchanging only a small amount of information, unless you use the NFC tap to establish a more persistent connection over a longer range and using faster technology, including Bluetooth, Wi-Fi, and Wi-Fi Direct. The WinRT API fully supports both of these scenarios.

NFC-Only Scenarios

When you exchange information via NFC, you must either send or receive a message encoded in the NFC Data Exchange Format (NDEF). This is a lightweight, platform-independent binary format for exchanging messages. The message allows one or more specific payloads (referred to as NDEF records) to be sent in a single package. Windows provides built-in support for a set of proprietary NDEF records that Windows 8.1 and Windows Phone devices can exchange. You can also format and exchange other types of records that target other platforms or are platform-independent by either building your own payload or using an open source library such as the NDEF Library for Proximity APIs that is available as a NuGet package.7

The ProximityExample project provides some examples of using the Proximity APIs defined in the Windows.Networking.Proximity namespace. The ProximityDevice class provides the simplest API to use and focuses specifically on short-range, short-duration NFC scenarios. To see whether the system has a proximity device available, simply call the GetDefault static method, shown in the constructor of the ViewModel class. Be sure to declare the Proximity capability in the application’s manifest.

this.proximityDevice = ProximityDevice.GetDefault();

The call returns null when a device is not present. If this is the case on your machine, you will not be able to take advantage of NFC exchanges and gestures, but you may still be able to create peer-to-peer connections using Bluetooth, Wi-Fi, or Wi-Fi Direct. You learn more about that in a later section. The proximity device exposes properties for its unique identifier, the maximum number of bytes it can send in a single message, and the bits per second it is capable of transmitting or receiving. You can also register for events that fire when another proximity device comes within range:

this.proximityDevice.DeviceArrived +=
this.proximityDevice.DeviceDeparted +=

The events are purely informational and do not provide any specific information. The ProximityDevice parameter of the handler is a reference back to the device that detected the event, which, in most cases, is the default device referenced in the constructor. Other classes exist for enumerating multiple proximity devices, in the rare case that the machine has multiple ones installed. This is a rare scenario because one NFC device is usually sufficient.

An easy way to share information with another NFC device is to use the PublishMessage method on the ProximityDevice class. This method is useful for sharing simple string data with other Windows or Windows Phone devices. It takes two parameters: the message type and the message itself. The message type is a unique identifier that enables other devices to determine how to handle the message. The message type always starts with a protocol, followed by a dot, followed by whatever custom identifier you prefer. In this case, the protocol must always be Windows. (The simple code for publishing and subscribing in this section is shared here for reference purposes but is not part of a specific example project.)

var publishedMessageId =
    "This is a simple message.");

The publication is not a transient event. The message will be available until you explicitly stop publishing, so multiple NFC devices over time can connect and subscribe for that message to receive it. To stop publishing, you call the StopPublishingMethod on the ProximityDevice.


If you want to know when the message has been transmitted, you can pass a MessageTransmittedHandler as a third parameter when you publish. The handler is called with the proximity device and the identifier for the message. You can use this to log that the message was transmitted, or even unsubscribe in the callback to ensure that the message is sent only once.

private void MessagePublished(ProximityDevice sender,
    long messageId)

To receive a message, you use the SubscribeForMessage method on the ProximityDevice class. You do not have to wait for a device to arrive or depart before you subscribe, and the subscription is valid for any device that publishes that particular message type. The subscription includes a handler that is called whenever the message is received, and it is provided a unique identifier that you can use to unsubscribe when you want to stop receiving the message.

var subscribedMessageId =

The method to receive the message is passed the ProximityDevice and a ProximityMessage. The message includes the data as a buffer, the data as a string, and the subscription ID, in case you want to use that to stop subscribing.

private void MessageReceived(ProximityDevice device,
    ProximityMessage message)
    var messageText = message.DataAsString;

The subscription method enables you to subscribe to any type of message. For messages that use non-Windows protocols, you need to decode the message. For example, the message type WindowsUri provides a URI, but you must first decode it from UTF16LE:

void messageReceivedHandler(ProximityDevice device,
    ProximityMessage message)
    var buffer = message.Data.ToArray();
    var uri = Encoding.Unicode.GetString(buffer, 0, buffer.Length);

Note that some devices, such as the Windows Phone, handle URIs at the operating system level. In other words, you cannot override the default behavior. The OS itself intercepts the NFC tag and opens the corresponding program. The program depends on the protocol. HTTP launches the Internet Explorer browser and navigates to the encoded web page, and a mailto protocol results in the default mail program being launched.

You can use the NFC API to write to smart tags, or special tags that use induction to store and publish information. Smart tags have varying capacities, depending on the manufacturer. Publishing to a smart tag always overwrites the data, and most smart tags have a lifetime of several hundred thousand writes. To get the capacity of a smart tag, you can subscribe to the WriteableTag message. This transmits an Int32 message that contains the capacity of the tag.

private void MessageReceived(ProximityDevice device,
    ProximityMessage message)
    var capacity = System.BitConvert.ToInt32(
        message.Data.ToArray(), 0);

Table 10.1 lists the various message types you can subscribe to.

TABLE 10.1 Common NFC Message Protocols




Consists of raw binary data.


Provides a custom string type proprietary to Windows, where * represents a custom type.


Consists of a UTF-16LE encoded URI string. Note that the operating system shell intercepts these messages and marshals them to the appropriate protocol handler.


Contains a specific MIME type—like image/jpeg for a bitmap image.


Published by smart tags when they come within range of reading or writing. Contains the capacity of the smart tag in bytes.


Consists of formatted NDEF records. Third-party libraries are available to easily encode and decode these record formats.

You also can publish messages for cross-platform compatibility or for the purpose of writing to smart tags. Instead of using the proprietary PublishMessage method, use the PublishBinaryMessage method. You can use this method to publish messages to other NFC devices, but it is also useful for writing messages to smart tags. The following code snippet encodes the URI to launch Skype and calls the echo service on a Windows or Windows Phone device.

var uri = new Uri("skype:echo123?call");
var buffer = Encoding.Unicode.GetBytes(uri.ToString());
var publishId = device.PublishBinaryMessage("WindowsUri:WriteTag",

Table 10.2 lists various protocols you can use when writing messages to tags.

TABLE 10.2 Message Protocols for Writing to Smart Tags




Publish binary data to a static smart tag


Write a URI to a static smart tag


Write a tag that launches an app with specific launch parameters


Write a cross-platform message using the NDEF format

To write a tag that launches an app, use the LaunchApp:WriteTag format; then provide a tab-delimited list that starts with the text to pass in as an argument and then includes pairs of platforms and application names. You can find the application name for a Windows 8.1 application in the application manifest. It is in the format of the Package family name (from the Packaging tab) and an exclamation mark. The following tag passes an argument named id with a value of 1 to both the Windows 8.1 ProximityExample app and a fictional app on Windows Phone 8 (the application name on Windows Phone is simply the GUID for the application ID).

var launchTag =
    "id=1\tWindows\tWinRTByExampleProximityExample_req6rhny9ggkj! " +
    "ProximityExample.App\tWindowsPhone\t{063e933a-fc8e-4f0c" +

If the app is present on the target device, it is launched with the arguments passed (the user is always prompted to opt in for the launch whenever this type of tag is encountered). If the app is not present, the device automatically takes the user to the app’s entry in the Windows Store. This makes the tag extremely useful: If you pass out smart tags with the encoding, users can easily discover and install your app, as well as subsequently launch it.

In this section, you learned ways to publish small messages that can be sent to other devices or encoded in smart tags. You also learned how to subscribe to and receive these messages. I mentioned earlier a way to share much more information than permitted by the limited bandwidth and speed of the NFC protocol. In this next section, you explore the tap-to-connect scenario that uses NFC to establish a persistent peer-to-peer connection for exchanging information.

Tap-to-Connect Scenarios

The PeerFinder class enables you to find and interact with other devices capable of peer-to-peer communications. Although a common use case is through NFC, you can also use Bluetooth and Wi-Fi Direct to locate and communicate with peers. The WinRT API abstracts these decisions from you and enables you to focus on the actual process of locating a peer and establishing a socket so that you can stream data back and forth.

Even if you don’t have a proximity device, chances are good that you can take advantage of the ProximityExample sample app to create a peer-to-peer connection. That’s because the WinRT API supports a browse scenario using Wi-Fi Direct, a technology that enables peer-to-peer wireless connections between devices that exists in most modern radios. Using the browsing scenario, you can install the app on two different devices and use them to discover each other.

The proximity APIs support finding peers running the same application. The application is defined by the package family, a unique identifier for your app that is shared across target platforms. For this reason, your app on a machine running Windows 8.1 can easily connect to the same app on a machine running Windows RT. You can also extend the peer to find instances of your app on other platforms, such as Windows Phone and Android. The PeerFinder class contains a dictionary named AlternateIdentities that hosts a list of platforms and application identifiers. In the previous section, you learned how to create a tag that launches the application and can contain multiple platforms and identities. You can add the same identifier to recognize that app as a peer like this:


You can discover and negotiate the peer connection either through an NFC tap gesture or by browsing Wi-Fi Direct. After the devices recognize each other and initiate the handshake, Windows tries to connect simultaneously using infrastructure (wireless or wired), Wi-Fi Direct, and Bluetooth. It uses whichever connection completes first (most likely, Bluetooth, when available) and passes the connection as an active socket to your app. You can restrict which connection types to allow by setting the static AllowBluetooth, AllowInfrastructure, and AllowWiFiDirect properties on the PeerFinder class.

The PeerSocket class in the example app provides a convenient way to manage a persistent socket connection. It takes a StreamSocket in the constructor and immediately creates a persistent reader and writer to interact with it.

public PeerSocket(StreamSocket socket)
    this.socket = socket;
    reader = new DataReader(socket.InputStream);
    writer = new DataWriter(socket.OutputStream);

It exposes a write method that uses the DataWriter to send a message to the socket and starts an infinite loop that runs on a background thread to listen for incoming messages. When it receives an incoming message, it raises an event so the app can register for the event, receive the message, and process it (in the case of the sample app, by marshalling it to the UI thread and showing it on the display). It also raises an error event whenever it encounters an error and disposes of both the reader and the writer when its own Dispose method is called.

To begin the process of connecting with a peer, you must first set your app to advertise. This broadcasts its identity over Wi-Fi Direct and makes it available for tap gestures if a proximity device is present. The Wi-Fi Direct mode is referred to as a browsed connect, and the NFC mode is referred to as a triggered connect. The PeerFinder class is instructed to begin advertising in the StartPeerFinder method on the ViewModel class.

First, the app registers to two events: the TriggeredConnectionStateChanged that is raised when an NFC tap gesture is received, and the ConnectionRequested event that is raised when another device browses your device and requests a connection.

PeerFinder.TriggeredConnectionStateChanged +=
PeerFinder.ConnectionRequested +=

Next, the role is set. Three possible roles exist. In the Peer role (included in the example app), two apps can connect with each other and communicate as peers. In a client/server scenario, one app can serve as the host and must set the Host role; then up to four other apps can connect using the Client role. Note that only Peer roles can browse to each other. The Host role can browse only Client roles, and vice versa.

PeerFinder.Role = PeerRole.Peer;

Finally, some discovery text is set. This is additional text you can share, such as an application name, an invitation to connect, information about the host system, or any other data up to 240 bytes in length. This data is broadcast and can be displayed when browsing. After the data is set, the PeerFinder starts advertising when you call the Start method.

PeerFinder.Role = PeerRole.Peer;
PeerFinder.DiscoveryData = Encoding.UTF8.GetBytes(

When both peers have started advertising, one of two scenarios can take place. The first is the NFC tap-to-connect scenario. When the proximity devices are tapped together, the TriggeredConnectionStateChanged event is raised. This event fires multiple times as the devices come within range and negotiate a connection.

The event handler for the triggered connection receives a State property of the type TriggeredConnectState (an enumeration). The handler on the viewmodel is called PeerFinderTriggeredConnectionStateChanged. The Listening state indicates that the proximity device is waiting for a tap. When the state is PeerFound or Connecting, the connection is being established and the handler simply updates the status for the user. If the connection fails, a Failed state is passed. The Completed state indicates success, and the arguments contain a Socket property with the active socket between the two devices:

case TriggeredConnectState.Completed:
    this.RouteToUiThread(() =>{this.IsConnecting = false;});

The InitializeSocket method sets up an instance of the PeerSocket to handle further communications. A state of Canceled means the connection was broken for some reason—for example, the devices moved out of range or a user intervention occurred.

The browse scenario starts when you request a list of available peers. The BrowseCommand method on the viewmodel calls the FindAllPeersAsync method and then loads the results to the list of available peers.

var peers = await PeerFinder.FindAllPeersAsync();

The user can then select a peer and request a connection. The connection is initiated in the ConnectCommand method.

var socket = await PeerFinder.ConnectAsync(

Note that the end result is the same as the triggered connection scenario: A socket is obtained and initialized to establish communications. The mode of the connection is transparent to your app, and there is no way to determine whether the connection was made using Bluetooth, infrastructure, or Wi-Fi Direct (unless you have restricted the allowable connection types to a single mode).

If your device is running a version of the app and the connection is requested from another device, a ConnectionRequested event is raised. The viewmodel handles this in the PeerFinderConnectionRequested method. In this scenario, you typically prompt the user to confirm that he or she wants to accept the request, and then either ignore the request or connect. The sample app automatically initiates the connection. The method to connect is identical for the host, client, or peer; the only difference is that, instead of passing a peer from a list of selections, the peer requesting the connection is passed as arguments to the event.

var socket = await PeerFinder.ConnectAsync(args.PeerInformation);

If the call succeeds for both peers, a connection is established and duplex communication can be initiated. You can transmit anything over the binary socket—from images, to streaming videos, to text or documents. The sample app simplifies the connection by transmitting only text. The text you enter is sent to the peer via the output stream of the socket, and any text received raises an event that is marshalled to the UI.

To use the sample program, install it on two Windows 8.1 devices that support Wi-Fi Direct or have proximity devices. The easiest way is to build and deploy the source, but you can also use the Store option on the Project Properties menu to create a side load package. Copy the package to a thumb drive and execute the included PowerShell script to install it on the other device.

Run the app on both devices. You must start advertising on both devices to establish a connection. After you’ve started advertising, either tap the devices or tap Browse to use Wi-Fi Direct. If you browse, select another machine and tap Connect. When the connection is established, via either NFC tap or browsing, you can begin to send messages between the two peers (see Figure 10.3).


FIGURE 10.3 Example of communicating between peers using the Proximity API

Numerous possibilities exist for taking advantage of the peer connection. You can use it to share documents or pictures between devices, archive data, create a chat session, or even share game state in a multiplayer game. The API handles all the necessary low-level handshakes and connectivity so that you can focus on the implementation of your application without worrying about the underlying NFC protocol or even whether the devices connect over Bluetooth or Wi-Fi Direct. The Proximity API is nearly identical on the Windows Phone, making it possible to build apps that span devices and create a truly continuous user experience among Windows PCs, tablets, and phones.

  • + Share This
  • 🔖 Save To Your Account