www.buildwindows.com Building Windows runtime sockets apps Dave Thaler Partner Software Design Engineer Microsoft Corporation Peter Smith Program Manager Microsoft Corporation PLAT-580T
Jan 19, 2016
www.buildwindows.com
Building Windows runtime sockets appsDave ThalerPartner Software Design EngineerMicrosoft Corporation
Peter SmithProgram ManagerMicrosoft Corporation
PLAT-580T
www.buildwindows.com
Agenda
• See how Windows runtime sockets makes developing TCP/UDP apps even easier
• Learn how to use proximity discovery for apps such as multiplayer games
• Learn how you traverse web proxies with a minimum of effort using WebSockets
You’ll leave with examples of how to• Use Windows Runtime sockets, WebSockets, and
proximity to add value to your app
www.buildwindows.com
Great apps are connected to services, devices, data, people
www.buildwindows.com
The Windows 8 platform makes it straightforward to build a great app that
people will buy, use and share.
Windows 8• makes basic networking even easier• enables new scenarios• provides consistent support for C++, C#, VB, and
JavaScript
www.buildwindows.com
Introducing Word Hunt
demo
www.buildwindows.com
Outline
• Simple API with lots of power• Integrated with runtime streams• Easy proximity discovery• Straightforward web proxy traversal with
WebSockets
Simplicity
www.buildwindows.com
Use sockets for custom protocols
Use higher-layer APIs instead for• Targeted scenarios• “Windows Share” and other contracts, Syndication, Sync,
Upload/Download• HTTP-based protocols• RESTful APIs, SOAP APIs
Use sockets when you have your own non-HTTP protocol
www.buildwindows.com
Families of APIs and abilities
Tile UpdateNotification
Service
SOAPWindows Communication
Foundation Windows Web Services
Proximity Discovery
Xbox LIVE
Download/Upload
Background Transfer
OAuthSkyDrive
Live IDConnected Accounts
Cost/CapsConnectionCost
Capabilities
SocketsWebSockets
Offline HTMLIndexedDB Application
Cache DOM Storage File API
SyndicationRSS AtomPub
HTTP/RESTWindows Communication
Foundation XHR HttpClient
HttpWebRequest IXHR
WebAuth Broker
Microsoft Web Services
High-level Foundational Helper
Stream Data
Reader+Writer
ContractsShare,
Settings, …
www.buildwindows.com
Families of APIs and abilities
Tile UpdateNotification Service
SOAPWindows Communication
Foundation Windows Web Services
Proximity Discovery
Xbox LIVE
Download/Upload
Background Transfer
OAuthSkyDrive
Live IDConnected Accounts
Cost/CapsConnectionCost
Capabilities
SocketsWebSockets
Offline HTMLIndexedDB Application
Cache DOM Storage File API
SyndicationRSS AtomPub
HTTP/RESTWindows Communication
Foundation XHR HttpClient HttpWebRequest IXHR
WebAuth Broker
Microsoft Web Services
High-level Foundational Helper
Stream Data
Reader+Writer
ContractsShare, Settings,
…
www.buildwindows.com
Refresher: TCP and UDP sockets
TCP and UDP are the lowest commonly-used network APIs; they are some of the oldest network protocols still used• TCP supports a reliable, ordered stream of bytes• UDP supports unreliable and unordered messages
Many other protocols (like POP email and SIP for Voice-Over-IP apps) are directly layered on top of TCP and UDP
www.buildwindows.com
Types of Windows Runtime sockets
• TCP protocol• ClientStreamSocket
• TCP protocol• Server
StreamSocketListener
• UDP protocol• PeerDatagramSocket
• WebSocket protocol (TCP-like)• ClientStreamWebSocket
• WebSocket protocol (UDP-like)• Client
MessageWebSocket
• Uses TCP or Bluetooth• Peer
ProximityStreamSocket
www.buildwindows.com
Let’s look at an example ofwhat’s simpler…
Get outgoing link speed of a socket’s interfaceBEFORE (.NET C# code)
public static long GetMaxSocketSendSpeed(TcpClient client){ IPAddress ipAddress = ((IPEndPoint)client.Client.LocalEndPoint).Address; NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters) { IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); UnicastIPAddressInformationCollection addrInfos = adapterProperties.UnicastAddresses;
foreach (UnicastIPAddressInformation addrInfo in addrInfos) { if (addrInfo.Address.Equals(ipAddress)) { return adapter.Speed; } } }
return 0;}
Windows 8:
public static long GetMaxSocketSendSpeed(StreamSocket client) { return client.Information.LocalHostName.NetworkAdapter.OutboundMaxBitsPerSecond; }
www.buildwindows.com
It’s simple to go from a socket to a rich set of other information.
Class relationshipsStreamSoc
ketControl
RemoteHostName
BandwidthStatistics
RoundTripTime
Statistics
Network Item
Connection Cost
OutputStream
InputStream
Win32 and .NET
Win32 only
New in Win8
StreamSocket
Information
LocalHostName
NetworkAdapter
Connection Profile
DataPlan Status
DataPlanUsage
StreamSocket
Previously in:
www.buildwindows.com
Expanded functionality
Want to get per-socket bandwidth and latency stats?• Use BandwidthStatistics, RoundTripTimeStatistics
Want to keep per-network or network-type state?• Use NetworkItem to identify network
Want to be cost-aware?• ConnectionProfile, ConnectionCost
Want data plan info?• DataPlanStatus, DataPlanUsage
www.buildwindows.com
Let’s dive into how to use runtime sockets…
Socket API Basics: initialize socket (C#)
// using Windows.Networking;// using Windows.Networking.Sockets;
var socket = new StreamSocket();
var hostName = new HostName("example.com");string serviceName = "4554";
// Connect using regular TCP (no security).await socket.ConnectAsync(hostName, serviceName, SocketProtectionLevel.PlainSocket);
// OPTIONAL: Enable SSL for security.await socket.ConnectAsync(hostName, serviceName, SocketProtectionLevel.Ssl);
www.buildwindows.com
HostName handles many things for youIPv6, internationalization, etc.
• Can be a DNS name (“example.com”) or• an IPv4 or IPv6 address literal (“2001:DB8::1”)
• Use HostName.IsEqual() to safely compare
RawName (input)
DisplayName CanonicalName
Example.Com Example.Com example.com
Example.xn--p1ai
Example.рф example.рф
10.000.000.001 10.0.0.1 10.0.0.1
0:0::1 ::1 ::1
www.buildwindows.com
ServiceName
What is the problem?• Existing code typically uses static port numbers• But just picking one runs danger of conflict!• Now harder to get an IANA reserved port number• IANA & IETF instead recommends static service
names with ephemeral ports
Solution• ServiceName can still be a port literal (“80”),
but now also allows a service name to resolve via DNS SRV!
Socket API Basics: send data (C#)
// using Windows.Storage.Streams;
var writer = new DataWriter(socket.OutputStream);
// There’s Write*() APIs for a large number of types.writer.WriteInt32(42);await writer.StoreAsync();
// OPTIONAL: Set endian-ness (defaults to LittleEndian).writer.ByteOrder = ByteOrder.BigEndian;
Socket API Basics: receive data (C#)
// using Windows.Storage.Streams;
var reader = new DataReader(socket.InputStream);
// Read in exactly 4 bytes of data.await reader.LoadAsync(4);
// There’s Read*() APIs for a large number of types.int number = reader.ReadInt32();
// Read in as many bytes as are available, up to 64K.reader.InputStreamOptions = InputStreamOptions.Partial;await reader.LoadAsync(64 * 1024);
Socket API Basics: close (C#)
// When the socket object falls out of scope,// it’s automatically closed.
}
// OPTIONAL: Close the socket.socket.Close();
www.buildwindows.com
Recap of Windows runtime sockets model• Familiar paradigm
• Consistent across C#, C++, VB, and JavaScript
• Easy to access related information
• Automatic support for IPv6 and internationalization
Runtime streams integration
www.buildwindows.com
Many things across the runtime use streams• Files• Images• Compression library• Crypto library• Background
upload/download • Webcam
• Video control• Microphone• Speakers• AtomPub media
resources• Inking strokes
www.buildwindows.com
Streams allow integrating and pipelining
Webcam SocketEncrypt
FileSocket
Mic
File
…
Speakers
Video control
…
Decrypt
Compress
Decompress
…
Filters OutputsInputs
Proximity discovery
www.buildwindows.com
To initiate a connection, you have to discover the remote endpoint somehow.
www.buildwindows.com
Typical discovery methods
• Type in a hostname
• Server (e.g., lobby) based
• Multicast, typically within a LAN
www.buildwindows.com
Word Hunt experience with hostnames
demo
www.buildwindows.com
Enter proximity discovery!
Proximity lets you TAP and CONNECT to another device• Uses Near Field Communications (NFC) radio• About a 4cm range• Works with all networking plus Wi-Fi direct and bluetooth
• Results in a connected StreamSocket• Or pass data like a URL, or use for discovery• Can even launch your app on the other device
• For more info, see talk [270] Connecting and sharing using Near Field Communication
Sample JavaScript codeWindows.Networking.Proximity.PeerFinder.allowBluetooth = false;Windows.Networking.Proximity.PeerFinder.onpeerconnectprogress = peerConnectProgressEventHandler;Windows.Networking.Proximity.PeerFinder.start();
function peerConnectProgressEventHandler(ev) { if (ev.connectState == Windows.Networking.Proximity.PeerConnectState.connectComplete) { socket = ev.proximityStreamSocket; if (socket.information.LocalHostName.canonicalName < socket.information.RemoteHostName.canonicalName) { onStreamSocketConnected(); } else { onStreamSocketAccepted(); } }}
www.buildwindows.com
Adding proximity discovery to Word Hunt
demo
Web proxy traversal
www.buildwindows.com
Problems caused by proxied connectivity
• TCP/UDP sockets don’t work with HTTP-only connectivity
Enterprise network
Internet
Web Proxy
XServer
www.buildwindows.com
WebSockets enable web proxy traversal
• BROWSERS could get through Web proxies • but couldn’t use sockets
• APPS had Sockets• but couldn’t easily get through web proxies
combine the best of both worlds.
Web
Sockets
www.buildwindows.com
Broadly available across frameworks
WebSockets Clients• Windows Runtime• IE 10
WebSockets Servers• System.Net• IIS• ASP.NET• WCF
Covered in this talk
Covered in [807] Building real-time webapps with WebSockets using IIS, ASP.NET and WCF
Covered in [373] Diving deep intoHTML5 Web Sockets
Sample C# code// Create a TCP-like WebSocket.var socket = new StreamWebSocket();
// Connect to a URI. “wss” means use TLS to secure connection.await socket.ConnectAsync(new Uri(“wss://example.com/demo”));
// After this point, use the socket just like a StreamSocket.
// OPTIONAL: Set any HTTP headers desired.socket.SetRequestHeader(“User-Agent”, “myapp”);
www.buildwindows.com
Converting a TCP app to WebSockets
demo
Review
www.buildwindows.com
Windows Runtime sockets
SimplicityStreams
Integration
ProximityDiscovery
Web ProxyTraversal
www.buildwindows.com
Related sessions
• [PLAT-785T] Creating connected apps that work on today's networks
• [PLAT-270T] Connecting and sharing with near field communication
• [SAC-807T] Building real-time web apps with WebSockets using IIS, ASP.NET and WCF
• [PLAT-373C] Building real-time web apps with HTML5 WebSockets
• [TOOL-588T] Debugging connected Windows 8 apps
www.buildwindows.com
Further reading and documentation
• Internationalized domain names: http://en.wikipedia.org/wiki/Internationalized_domain_name
• Word Hunt app
• Please visit the forums on the Windows Dev Center at http://forums.dev.windows.com• For best response, please include the Build Session # in
the title of your post
www.buildwindows.com
• Feedback and questions http://forums.dev.windows.com
• Session feedbackhttp://bldw.in/SessionFeedback
thank you
© 2011 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.