480 likes | 1.35k Views
PLAT-580T. Building Windows runtime sockets apps. Dave Thaler Partner Software Design Engineer Microsoft Corporation Peter Smith Program Manager Microsoft Corporation. Agenda. See how Windows runtime sockets makes developing TCP/UDP apps even easier
E N D
PLAT-580T Building Windows runtime sockets apps Dave Thaler Partner Software Design Engineer Microsoft Corporation Peter Smith Program Manager Microsoft Corporation
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
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
demo Introducing Word Hunt
Outline • Simple API with lots of power • Integrated with runtime streams • Easy proximity discovery • Straightforward web proxy traversal with WebSockets
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
Families of APIs and abilities Microsoft Web Services High-level Foundational Helper Tile Update Notification Service Contracts Share, Settings, … HTTP/REST Windows Communication Foundation XHR HttpClient HttpWebRequest IXHR Cost/Caps ConnectionCost Capabilities Live ID Connected Accounts Download/Upload Background Transfer Syndication RSS AtomPub WebAuth Broker SkyDrive Proximity Discovery SOAP Windows Communication Foundation Windows Web Services OAuth Xbox LIVE Offline HTML IndexedDB Application Cache DOM Storage File API Sockets WebSockets Stream Data Reader+Writer
Families of APIs and abilities Microsoft Web Services High-level Foundational Helper Tile Update Notification Service Contracts Share, Settings, … HTTP/REST Windows Communication Foundation XHR HttpClient HttpWebRequest IXHR Cost/Caps ConnectionCost Capabilities Live ID Connected Accounts Download/Upload Background Transfer Syndication RSS AtomPub WebAuth Broker SkyDrive Proximity Discovery SOAP Windows Communication Foundation Windows Web Services OAuth Xbox LIVE Offline HTML IndexedDB Application Cache DOM Storage File API Sockets WebSockets Stream Data Reader+Writer
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
Get outgoing link speed of a socket’s interfaceBEFORE (.NET C# code) • publicstaticlongGetMaxSocketSendSpeed(TcpClient client) • { • IPAddressipAddress = ((IPEndPoint)client.Client.LocalEndPoint).Address; • NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); • foreach (NetworkInterface adapter in adapters) { • IPInterfacePropertiesadapterProperties = adapter.GetIPProperties(); • UnicastIPAddressInformationCollectionaddrInfos = • adapterProperties.UnicastAddresses; • foreach (UnicastIPAddressInformationaddrInfoinaddrInfos) { • if (addrInfo.Address.Equals(ipAddress)) { • returnadapter.Speed; • } • } • } • return 0; • } Windows 8: publicstaticlongGetMaxSocketSendSpeed(StreamSocket client) { return client.Information.LocalHostName.NetworkAdapter.OutboundMaxBitsPerSecond; }
It’s simple to go from a socket to a rich set of other information.
Class relationships StreamSocket StreamSocket Control StreamSocket Information InputStream OutputStream Bandwidth Statistics Remote HostName Local HostName RoundTripTime Statistics Network Adapter Connection Profile Network Item Previously in: Connection Cost DataPlan Status Win32 and .NET Win32 only DataPlan Usage New in Win8
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
Socket API Basics: initialize socket (C#) • // using Windows.Networking; • // using Windows.Networking.Sockets; • varsocket = newStreamSocket(); • varhostName = newHostName("example.com"); • stringserviceName = "4554"; • // Connect using regular TCP (no security). • awaitsocket.ConnectAsync(hostName, serviceName, • SocketProtectionLevel.PlainSocket); // OPTIONAL: Enable SSL for security. await socket.ConnectAsync(hostName, serviceName, SocketProtectionLevel.Ssl);
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
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; • varwriter = newDataWriter(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; • varreader = newDataReader(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#) • // OPTIONAL: Close the socket. • socket.Close(); • // When the socket object falls out of scope, • // it’s automatically closed. • }
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
Many things across the runtime use streams • Files • Images • Compression library • Crypto library • Background upload/download • Webcam • Video control • Microphone • Speakers • AtomPubmedia resources • Inking strokes
Streams allow integrating and pipelining Inputs Outputs Filters Socket Webcam Encrypt Decrypt File Socket Mic Compress Speakers Video control File Decompress … … …
To initiate a connection, you have to discover the remote endpoint somehow.
Typical discovery methods • Type in a hostname • Server (e.g., lobby) based • Multicast, typically within a LAN
demo Word Hunt experience with hostnames
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 code • Windows.Networking.Proximity.PeerFinder.allowBluetooth=false; • Windows.Networking.Proximity.PeerFinder.onpeerconnectprogress= • peerConnectProgressEventHandler; • Windows.Networking.Proximity.PeerFinder.start(); • functionpeerConnectProgressEventHandler(ev){ • if(ev.connectState== • Windows.Networking.Proximity.PeerConnectState.connectComplete){ • socket =ev.proximityStreamSocket; • if(socket.information.LocalHostName.canonicalName< • socket.information.RemoteHostName.canonicalName){ • onStreamSocketConnected(); • }else{ • onStreamSocketAccepted(); • } • } • }
demo Adding proximity discovery to Word Hunt
Problems caused by proxiedconnectivity Web Proxy • TCP/UDP sockets don’t work with HTTP-only connectivity Internet Enterprise network X Server
WebSocketsenable web proxy traversal • BROWSERS could get through Webproxies • but couldn’t use sockets • APPS had Sockets • but couldn’t easily get through web proxies Web Sockets combine the best of both worlds.
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 web apps with WebSockets using IIS, ASP.NET and WCF Covered in [373] Diving deep into HTML5 Web Sockets
Sample C# code // OPTIONAL: Set any HTTP headers desired. socket.SetRequestHeader(“User-Agent”, “myapp”); • // Create a TCP-like WebSocket. • varsocket = newStreamWebSocket(); • // 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.
demo Converting a TCP app to WebSockets
Windows Runtime sockets Simplicity Streams Integration Web Proxy Traversal Proximity Discovery
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
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
thank you Feedback and questions http://forums.dev.windows.com Session feedbackhttp://bldw.in/SessionFeedback
© 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.