1 / 48

Building Windows runtime sockets apps

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

onella
Télécharger la présentation

Building Windows runtime sockets apps

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PLAT-580T Building Windows runtime sockets apps Dave Thaler Partner Software Design Engineer Microsoft Corporation Peter Smith Program Manager Microsoft Corporation

  2. 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

  3. Great apps are connected to services, devices, data, people

  4. 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

  5. demo Introducing Word Hunt

  6. Outline • Simple API with lots of power • Integrated with runtime streams • Easy proximity discovery • Straightforward web proxy traversal with WebSockets

  7. Simplicity

  8. 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

  9. 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

  10. 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

  11. 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

  12. Types of Windows Runtime sockets

  13. Let’s look at an example ofwhat’s simpler…

  14. 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; }

  15. It’s simple to go from a socket to a rich set of other information.

  16. 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

  17. 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

  18. Let’s dive into how to use runtime sockets…

  19. 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);

  20. 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

  21. 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!

  22. 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;

  23. 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);

  24. Socket API Basics: close (C#) • // OPTIONAL: Close the socket. • socket.Close(); • // When the socket object falls out of scope, • // it’s automatically closed. • }

  25. 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

  26. Runtime streams integration

  27. 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

  28. Streams allow integrating and pipelining Inputs Outputs Filters Socket Webcam Encrypt Decrypt File Socket Mic Compress Speakers Video control File Decompress … … …

  29. Proximity discovery

  30. To initiate a connection, you have to discover the remote endpoint somehow.

  31. Typical discovery methods • Type in a hostname • Server (e.g., lobby) based • Multicast, typically within a LAN

  32. demo Word Hunt experience with hostnames

  33. 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

  34. 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(); • } • } • }

  35. demo Adding proximity discovery to Word Hunt

  36. Web proxy traversal

  37. Problems caused by proxiedconnectivity Web Proxy • TCP/UDP sockets don’t work with HTTP-only connectivity Internet Enterprise network X Server

  38. 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.

  39. 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

  40. 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.

  41. demo Converting a TCP app to WebSockets

  42. Review

  43. Windows Runtime sockets Simplicity Streams Integration Web Proxy Traversal Proximity Discovery

  44. 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

  45. 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

  46. thank you Feedback and questions http://forums.dev.windows.com Session feedbackhttp://bldw.in/SessionFeedback

  47. © 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.

More Related