optional: set some custom name to identify self to others. peerfinder.displayname = mynametodisplay;...
TRANSCRIPT
Tips and tricks for developing connected applicationsDave ThalerPartner Software Design Engineer
Kushal NarkhedeSenior Software Design Engineer
Session 3-127
Agenda
Learn how to use Wi-Fi Direct to discover nearby application instances – for example, for multiplayer games
Learn tips for creating a great experience with your connected app
Learn how to easily connect streams
Learn how to secure connections with a minimum of effort using SSL
Windows 8 makes basic networking easier, enables new scenarios, and has cross-language supportSome relevant //build/ 2011 talks:[785] Creating connected apps that work on today's networks[580] Building Windows runtime sockets apps[581] Making apps social and connected with HTTP services
Today, we’ll talk about additional features, tips, and tricks based on questions we’ve heard from you
Most Windows Store apps are “connected”
Demo:Word Hunt
Local area Wi-Fi discovery
To initiate a connection, you have to discover the remote endpoint
Typical discovery methods
Type in a hostname
Server (e.g., lobby) based
Tap
Multicast within local area, such as within a LAN
- See talk [580] from //build/ 2011
Concepts
Service: all listening instances of my app
Instance: app running on a specific machine
Endpoint: address/port
Using Wi-Fi Direct to discover and connectDiscover: Given a service, find nearby instances Service = Your app Instance = Windows.Networking.Proximity.PeerInformation
Connect: Given an instance, open a session to an endpoint Instance = Windows.Networking.Proximity.PeerInformation Session = Windows.Networking.Sockets.StreamSocket Endpoint = socket.Information.Remote{Address,Port}
See also Proximity sample on MSDN
Listening with PeerFinder: C# example// OPTIONAL: Set some custom name to identify self to others.
PeerFinder.displayName = myNameToDisplay;
PeerFinder.ConnectionRequested += new TypedEventHandler<object, ConnectionRequestedEventArgs>(PeerConnectionRequested);PeerFinder.Start(); // Start advertising.
private async void PeerConnectionRequested(object sender, ConnectionRequestedEventArgs args) { PeerInformation peer = args.PeerInformation;
rootPage.NotifyUser("Connection requested from peer " + peer.DisplayName); // ... Confirm as appropriate ...
StreamSocket socket = await PeerFinder.ConnectAsync(peer);}
Connecting with PeerFinder: C# exampleusing Windows.Networking.Proximity;
IReadOnlyList<PeerInformation> peerList;
// OPTIONAL: Set some custom name to identify self to others.Windows.Networking.Proximity.PeerFinder.displayName = myNameToDisplay;
PeerFinder.Start(); // Must be done before FindAllPeersAsync().peerList = await PeerFinder.FindAllPeersAsync(); // Scan for ~1 second.
// ... Use peerList[index].displayName to select index ...
StreamSocket socket = await PeerFinder.ConnectAsync(peerList[index]);PeerFinder.Stop(); // Done with discovery.
Symmetric discovery experienceSimplify the user experience by enabling symmetric discovery
You don’t have to ask the user to choose to be a host or client
Allows a simpler two-player experience
Demo:Using Wi-Fi Direct with Word Hunt
API usage tips
DisplayName should be a unique string, such as the user name, gamertag, etc. (defaults to machine name) Consider impact on your privacy policy statement
Design user experience to support both tap and browse PeerFinder API usage supports both, if hardware support exists
Use PeerFinder.SupportedDiscoveryTypes to check support PeerDiscoveryTypes.Browse: Wi-Fi Direct PeerDiscoveryTypes.Triggered (tap): near-field communication (NFC)
Wi-Fi Direct tips
Can only connect to one peer at a time, across all apps If another app connects, your app loses its connection, so be
prepared to reconnect
Wi-Fi Direct can’t advertise and discover at the same time, so if symmetric experience then use a random delay between FindAllPeersAsync() calls or a refresh button Advertising/scanning happens only when app is the foreground app
Building great connected experiences
Tips for writing connected apps
White paper Developing connected applications on MSDN:
1. Pick the right API for your scenarios2. Pick the right capabilities3. Adapt app behavior for metered networks4. React to network status changes
[580]*
[785]*
[588]*
*//build/ 2011 talk
Adapt behavior for metered networksWindows.Networking.Connectivity.ConnectionCost NetworkCostType: Unrestricted, Fixed, Variable, Unknown Roaming: Whether outside home provider OverDataLimit: Whether usage has exceeded data plan allowance
Suggested behaviors: Normal: Unrestricted and not Roaming Conservative: Fixed/Variable, but not Roaming or OverDataLimit Opt-in: Roaming or OverDataLimit
See talk [785] from //build/ 2011
Be power efficient
Often the same guidance as being cost efficient
Less bandwidth use means less powerKeeping radio up less means less power
Cache content to conserve bandwidth
Avoid frequent periodic messages
Cache content to conserve bandwidthSome APIs do caching for you:- Windows.Web.Syndication (configurable via
BypassCacheOnRetrieve)- xhr, IXHR2- StorageFile
For other APIs, app should do its own caching as appropriate:- HttpClient- BackgroundTransfer
Using caching also helps you support an offline mode to improve experience
Avoid frequent periodic messagesSending periodic messages every (say) 30 seconds is inefficient
Wireless radios drop to lower power state only after an idle period
Batch and wait long periods as much as you can
Use Windows Push Notification Services (WNS) if you must receive notifications (talk [863] from //build/ 2011)
Connecting streams
Streams allow integrating and pipelining
Webcam SocketEncrypt
FileSocket
Mic
File
…
Speakers
Video control
…
Decrypt
Compress
Decompress
…
Filters OutputsInputs
Use CopyAsync to easily connect streams
StreamSocket connectedSocket;StorageFile file;
// Get stream from file.var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);
await RandomAccessStream.CopyAsync(connectedSocket.InputStream, fileStream);
Socket File
Use CopyAsync to easily connect streamsSocket FileDecompress
StreamSocket connectedSocket;StorageFile file;
// Get stream from file.var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);
await RandomAccessStream.CopyAsync(connectedSocket.InputStream, fileStream);
Use CopyAsync to easily connect streamsSocket FileDecompress
StreamSocket connectedSocket;StorageFile file;
// Get stream from file.var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);
var decompressor = new Windows.Storage.Compression.Decompressor( connectedSocket.InputStream);
await RandomAccessStream.CopyAsync(decompressor, fileStream);
Decryption exampleSocket FileDecrypt
StreamSocket connectedSocket;StorageFile file;
// Get stream from file.var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);
var provider = new Windows.Security.Cryptography.DataProtection. DataProtectionProvider();
await provider.UnprotectStreamAsync(connectedSocket.InputStream, fileStream);
Securing connections
SSL/TLS is supported by many APIs
StreamSocket: SocketProtectionLevel.Ssl, UpgradeToSslAsync
MessageWebSocket, DatagramWebSocket: “wss:” URIs
HttpClient, xhr, IXHR2: “https:” URIs
BackgroundTransfer: “https:” URIs
Why wasn’t SSL/TLS already used more?Hard to provision server with a certificate?
Using self-signed certs makes this easy!
Hard to code client to use with sockets or HTTP APIs?
Windows 8 makes this easy!
Let’s see how easy…
Demo:Securing a connection
Loopback
Customer confidence in Windows Store apps helps you make money
Customer confidenceWe want customers to feel that Windows Store apps are safe- We defined ways to safely interact with the rest of the system
Classic desktop apps still have access to the full power of Windows- They can still do the less-safe things
Thus, Windows Store apps aren’t allowed to talk to desktop apps- Not via sockets, files, RPC, named pipes, or other types of IPC- If you need to do so, use a desktop app
“Then how can I test?”Windows Store apps actually can talk to desktop apps, but only on dev machines
- Store certification won’t accept loopback
Visual Studio auto-registers loopback exemption on local machine- To view the list: CheckNetIsolation.exe LoopbackExempt –s- Can also manually add/remove exemptions using CheckNetIsolation.exe
For more information:- “
How to enable loopback and troubleshoot network isolation (Windows Store apps)” on MSDN
- Talk [588] from //build/ 2011
Loopback also works for other cases
Loopback within an app works great Example: Word Hunt “hosting” component accepts socket
connections from both the local application (via loopback) and a remote player
Loopback between desktop apps using WinRT sockets also works great Networking APIs aren’t just for Windows Store apps!
Review
Tips
1. Use Wi-Fi Direct to discover nearby peers2. Use appropriate APIs and timer intervals for power
efficiency3. Use CopyAsync to easily connect streams4. Use self-signed certs to easily secure connections5. Use CheckNetIsolation.exe to test on same machine
For more information//build/ 2011 sessions:
[785] Creating connected apps that work on today's networks
[580] Building Windows runtime sockets apps
[581] Making apps social and connected with HTTP services
[329] Understanding Wi-Fi Direct in Windows 8
[588] Debugging Connected Apps
[863] Delivering notifications with the Windows Push Notification Service and Windows Azure
Documentation on MSDN:
Proximity sample
Developing connected applications
How to enable loopback and troubleshoot network isolation
• Develop: http://msdn.microsoft.com/en-US/windows/apps/br229512
• Design: http://design.windows.com/
• Samples: http://code.msdn.microsoft.com/windowsapps/Windows-8-Modern-Style-App-Samples
• Videos: http://channel9.msdn.com/Windows
Resources
Please submit session evals by using the Build Windows 8 appor at http://aka.ms/BuildSessions
© 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.