Date post: | 15-Apr-2017 |
Category: |
Technology |
Upload: | windows-developer |
View: | 744 times |
Download: | 0 times |
#Build2016
Using the right networking APIs for your Universal Windows appSidharth Nabar, Himadri SarkarWindows Networking team
Server-side support
Scenario requirement
s
Foreground vs
background
Portability requirement
s
Performance consideratio
nsEase of coding
Considerations when writing a networking app
Which API should you use?
Discuss 4 networking scenarios & API Choices for each
In this talk
HTTPS with user authentication
Device-Cloud bi-directional communication
Network communication between devices over socketsDownload/Upload content to cloud in the background
HTTPS with User Authentication
Scenario 1
• Client Authentication• Username/Password or certificate?• UI or Programmatic?
• Server Authentication• Well-known or private CA?• Custom validation/Certificate pinning?
Features
Recommended API: HttpClient
Windows.Web.Http & System.Net.HttpAPI Choices
Feature Windows.Web.Http
System.Net.Http
Programming Language support All UWP languages C#/VB
Private CA/Self-signed certificate √ √Custom validation of server certificate
√ (new!) X (on roadmap)
Integration with native UI for Auth
√ X
Client Certificate Support √ Partial
Cross-platform support (Xamarin)
X √
Programming Pattern – Windows.Web.Http1. Create an HttpBaseProtocolFilter instance (optional)
var filter = new HttpBaseProtocolFilter();
2. Modify settings on the filter (optional)
filter.ClientCertificate = myCertificate;
3. Create an HttpClient instance
var client = new HttpClient(); ORvar client = new HttpClient(filter);
4. Send requests from client
HttpResponseMessage response = await client.GetAsync(uri);
Demo: Online Auction AppRequirements:1. Custom server certificate validation2. Client Certificate
API Choice:Windows.Web.Http.HttpClient
Summary: HTTPS with User Authentication• Windows.Web.Http
Supports wide range of HTTP security and authentication features
Available for all UWP programming languages
• System.Net.Http Supports programmatic use of credentials and certificatesAvailable cross-platform for C#/VB developers
(For more info and code snippets, see http://aka.ms/httpclientblogpost)
Device-Cloud Bidirectional
Communication
Scenario 2
• Communication Model• Truly bidirectional or client-initiated?• Half-duplex or full-duplex?
• Server Endpoint• REST API or simple message exchange?• Supports WebSockets?
• Performance Requirements/Optimizations• Caching/Data Compression required?• Latency/delay requirements?
Features
Windows.Web.Http.HttpClient&Windows.Networking.Sockets.WebSockets
API Choices
Feature HttpClient WebSockets
Messaging pattern Request-response Bidirectional
Duplex communication? Half Full
Latency/overhead Higher Lower
Proxy/Firewall traversal √ √Server certificate custom validation
√(new!) √ (new!)
REST support, CRUD semantics Built-in Needs additional code
Caching and data compression Built-in Needs additional code
MessageWebSocket & StreamWebSocket
API Choices (Contd.)
Feature MessageWebSocket
StreamWebSocket
Message Format Discrete WebSocket messages
Continuous data stream
UTF-8 Strings/JSON data √ X
Binary data √ √
Recommended data size Small (bytes/KB) Large (MB)
Recommended content types Strings, JSON content
Audio, Video, Photos
Programming Pattern – MessageWebSocket1. Create an instance of WebSocket
var socket= new MessageWebSocket();
2. Register MessageReceived event handler
socket.MessageReceived = myReceivingHandler;
3. Register Closed event handler
socket.Closed = myClosedHandler;
4. Connect to server and send data. Close connection with status code at the end.
await socket.ConnectAsync(serverUri);// Send data.socket.Close(code, reason);
Demo: Online Auction AppRequirements:1. Client-Server bidirectional communication2. Server relays others’ bids independent of
client’s bids3. Minimum latency and overhead
API Choice:Windows.Networking.Sockets.MessageWebSocket
Network Traffic Comparison
Wireshark trace for WebSocket run
Wireshark trace for HttpClient runBytes on the wire
Summary: Device-Cloud bidirectional communication• HttpClient
Ideal for request-response communicationBuilt-in support for REST API and message handling semantics
• WebSockets Ideal for low latency bidirectional communicationMessage format and semantics need to be implemented on top
Network communication between devices over
sockets
Scenario 3
• Lifespan of the socket• Foreground only or Background also
• Language Choice• C#/VB, JavaScript or C++
• Pre-existing code• Win32 or .NET libraries
Features
API Choices
Feature Windows.Networking.Sockets
System.Net.Sockets
WinSock
Language Support
C++/CX √ X √JavaScript
√ X X
C#/VB √ √ XActivity Support in Background
√ X X
Windows.Networking.Sockets, System.Net.Sockets and Winsock
•Special trigger to start a background task – SocketActivityTrigger
•App can transfer ownership of socket to the OS while suspending
•OS keeps the socket alive even when the app is not running
Sockets – Listening in Background
Programming Pattern – Sockets in Background1. Create a task with trigger type SocketActivityTrigger
socketTaskBuilder.TaskEntryPoint = "SocketActivityBackgroundTask.SocketActivityTask";var trigger = new SocketActivityTrigger();socketTaskBuilder.SetTrigger(trigger);var task = socketTaskBuilder.Register();
2. Associate Socket with the task and connect to the remote device
socket.EnableTransferOwnership(task.TaskId, SocketActivityConnectedStandbyAction.Wake); await socket.ConnectAsync(target, port);
Things to note:• At any point ownership of the socket can be only in one
component• Find the list of sockets owned by the service using:
SocketActivityInformation.AllSockets• Socket not in the list means socket is already closed or
retrieved
Programming Pattern – Sockets in Background3. Transfer the ownership
when suspending foreground app or Background Task cancellation
socket.TransferOwnership(socketId);
Demo: Multi-player GameRequirements:1. App communication between devices over sockets2. Listening on the socket activity even when the app is
not running
API Choice:Windows.Networking.Sockets
• Sockets APIs in UWPRecommended: Windows.Networking.SocketsAlso available: System.Net.Socket, Winsock
• Listening on Socket in backgroundUse SocketActivityTrigger
Summary
Download/Upload content to cloud in the background
Scenario 4
• Protocol• HTTP/ FTP
• Destination location• Memory/File
• Content Size• Small (in KBs)/Big (in MBs)
• Resiliency to reboot and network outage• Resource Awareness• Battery/Network cost
Features
HttpClient (in background task) & BackgroundTransfer
API Choices
Feature HttpClient in BG Task Windows.Networking.Backgroun
dTransferProtocol HTTP HTTP/FTPDestination Location In memory & File File onlyRecommended file size Small (KBs) Large (MBs)
Resiliency (network connection drop/reboot)
Needs additional code Can be resumed where left off
Network Cost Awareness Needs additional code Built-inBattery Saver Awareness Needs additional code Built-in
Programming Pattern – Windows.Networking.BackgroundTransfer1. Create an DownloadOperation instance
BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(new Uri(downloadlocation), file);
2. Start the transfer Task<DownloadOperation> startTask = download.StartAsync().AsTask();
3. Retrieve and attach to the transfers
downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();await download.AttachAsync().AsTask(cts.Token, progressCallback);
Programming Pattern – Windows.Networking.BackgroundTransfer4.Handling of Completion in foreground app
Task<DownloadOperation> startTask = download.StartAsync().AsTask();Task continueTask = startTask.ContinueWith(OnDownloadCompleted);
5.Handling of Completion using a background task
BackgroundTransferCompletionGroup completionGroup = new BackgroundTransferCompletionGroup();//Create background task builderbuilder.SetTrigger(completionGroup.Trigger);BackgroundDownloader downloader = new BackgroundDownloader(completionGroup);
Demo: Multi-player GameRequirements:1. Download a new game level in the Background2. Show a toast notification on completion of the
download
API Choice:Windows.Networking.BackgroundTransfer
• BackgroundTransfer APIs in UWPRecommended for large files For smaller size/in-memory content - HTTPClient in background task
• Automatic completion handlingUse trigger in BackgroundTransferCompletionGroup
Summary – Download/Upload content in Background
• MSDN: http://aka.ms/NetworkApiChoice• GitHub Universal Samples:
https://github.com/Microsoft/Windows-universal-samples/• HttpClient• WebSockets• SocketActivityStreamSocket• BackgroundTransfer
• API Feedback: http://aka.ms/WinDevUserVoice
References and More Info
© 2016 Microsoft Corporation. All rights reserved.
Thank You!