Dela via


StreamSocket Class

Definition

Supports network communication using a stream socket over TCP or Bluetooth RFCOMM in UWP apps.

public ref class StreamSocket sealed : IClosable
/// [Windows.Foundation.Metadata.Activatable(65536, Windows.Foundation.UniversalApiContract)]
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class StreamSocket final : IClosable
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
/// [Windows.Foundation.Metadata.Activatable(65536, "Windows.Foundation.UniversalApiContract")]
class StreamSocket final : IClosable
[Windows.Foundation.Metadata.Activatable(65536, typeof(Windows.Foundation.UniversalApiContract))]
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public sealed class StreamSocket : System.IDisposable
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
[Windows.Foundation.Metadata.Activatable(65536, "Windows.Foundation.UniversalApiContract")]
public sealed class StreamSocket : System.IDisposable
function StreamSocket()
Public NotInheritable Class StreamSocket
Implements IDisposable
Inheritance
Object Platform::Object IInspectable StreamSocket
Attributes
Implements

Windows requirements

Device family
Windows 10 (introduced in 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced in v1.0)
App capabilities
bluetooth.rfcomm ID_CAP_NETWORKING [Windows Phone] internetClient privateNetworkClientServer

Examples

Sample applications that use this class include Bluetooth RFCOMM chat sample, DatagramSocket sample (Windows 10), Socket activity trigger stream socket sample, StreamSocket sample (Windows 10), and Wi-Fi Direct sample.

Remarks

The StreamSocket class supports network communications that use a stream socket over TCP or Bluetooth RFCOMM in UWP apps.

For a client app, the most common sequence of operations using a StreamSocket are the following:

  • Create the StreamSocket.
  • Get a StreamSocketControl object using the Control property and set any properties on the StreamSocketControl object before calling one of the ConnectAsync methods.
  • Call one of the ConnectAsync methods to establish a connection with the remote endpoint. For Bluetooth, the remote service name is a Bluetooth Service ID. If an SSL/TLS connection for TCP or a level of encryption for Bluetooth is required immediately, this can be specified using some of the ConnectAsync methods. If an SSL/TLS connection is desired after sending and receiving some initial data for a TCP socket, then the UpgradeToSslAsync method can be called later to upgrade the connection to use SSL.
  • Get the OutputStream property to write data to the remote host.
  • Get the InputStream property to read data from the remote host.
  • Read and write data as needed.
  • Call the Close method to disconnect the socket, abort any pending operations, and release all unmanaged resources associated with the StreamSocket object.

Note

The Close method is used by UWP apps written in JavaScript. For apps written using the .NET Framework 4.5 in C# and VB.NET, the Close method is exposed as the method on the StreamSocket. For apps written in C++, the Close method will be called when using the delete keyword on the object.

Explicitly closing a StreamSocket object (calling the Close method) will ensure a graceful disconnect if no pending read or write operations exist on the socket. All pending reads are automatically aborted and the StreamSocket waits for any ongoing I/O to complete before tearing down the connection. If no unread data remains on the socket after the ongoing I/O is finished, a graceful disconnect (FIN) is guaranteed to occur. Otherwise, an ungraceful disconnect (RST) occurs.

When an active (still connected) StreamSocket object goes out of scope, an abortive (non-graceful) disconnect may result, which can lead to previously-sent data being discarded before it is read by the remote peer. It is strongly recommended that Close (the Close method in JavaScript, the method in C# and VB.NET, or the delete operator in C++) be called on a StreamSocket object before it goes out of scope.

Whenever a read or write operation is cancelled, the I/O operation completes with Error state and the associated StreamSocket object immediately tears down the connection, which leads to an ungraceful disconnect (RST) if any unread or unsent data remains on the socket.

Ungraceful disconnects (RST) will always occur if: An abnormal termination occurs (for example, the app crashes); or an abnormal connection failure is detected by the networking stack (for example, TCP retransmit timeout).

The StreamSocket object is also used in conjunction with the StreamSocketListener object to listen for incoming connections over TCP or Bluetooth RFCOMM in server apps or peer-to-peer apps. A StreamSocket object is returned by the Socket property on the ConnectionReceived event when a StreamSocketListener object receives a TCP or Bluetooth RFCOMM connection request. For more information, see StreamSocketListener.

Support for proxies

In a UWP app, the StreamSocket class supports connecting to a remote endpoint when proxies are required to complete the connection. This support for proxies is automatic and transparent to the app. A StreamSocket can establish a connection through authenticating proxies as well as through other proxies where authentication is not needed. Authenticating proxies only work if Internet Explorer or an app that uses the HttpClient class in the Windows.Web.Http namespace has previously successfully authenticated with the proxy and the credentials previously used for the authentication are still valid. The support for authenticating proxies does not work if a web browser other than Internet Explorer was used to provide the authentication credentials to the proxy. Connecting through proxies is not supported if a local host address or a specific network adapter is specified on the ConnectAsync method.

In a UWP app, the ConnectAsync methods on the StreamSocket object try to discover proxies and the current proxy configuration both before and after name resolution to help speed up connection establishment. If a port is specified for the endpoint rather than a service name, both proxy discovery and name resolution are initiated internally. If proxy discovery completes before name resolution and the CanConnectDirectly property on the ProxyConfiguration object is false, then a proxy connection will be attempted. Once name resolution completes, proxy discovery is initiated again with the resolved endpoint address to determine the current proxy configuration. If CanConnectDirectly indicates after name resolution that the app can connect directly to the remote endpoint, then a socket connection will be attempted directly to the endpoint. If CanConnectDirectly is false after name resolution, then a socket connection will be attempted directly to the endpoint and a parallel socket connection is attempted through the proxy. The first connection to succeed is used by the StreamSocket and the other connection is canceled.

There may be cases where CanConnectDirectly returns false, yet it does not mean you cannot access the resource directly. A local network could be configured to have support for both a proxy and network address translation (NAT). The WPAD script used to supply proxy information to a web browser or HttpClient tells Windows that it should use the proxy. This can cause problems when the remote endpoint is not expecting a proxy connection (an HTTP CONNECT request, for example). An app can use the GetProxyConfigurationAsync method on the NetworkInformation object passing the remote endpoint and port for the uri parameter to retrieve proxy information to help determine when this condition is suspected. A way to avoid proxy connection requests from being sent when a server can only handle direct connections is to use the ConnectAsync(HostName, String, SocketProtectionLevel, NetworkAdapter) method, since the proxy-related logic is disabled when a specific network adapter is selected.

In a Windows Phone 8.x app, the StreamSocket does not provide automatic support for proxies since the ProxyConfiguration class is not supported on Windows Phone.

Handling exceptions

You must write code to handle exceptions when you call asynchronous methods on the StreamSocket class. Exceptions can result from parameter validation errors, name resolutions failures, and network errors. Exceptions from network errors (loss of connectivity, connection failures, and server failures, for example) can happen at any time. These errors result in exceptions being thrown. If not handled by your app, an exception can cause your entire app to be terminated by the runtime.

The Windows.Networking.Sockets namespace has features that simplify handling errors when using sockets. The GetStatus method on the SocketError class can convert the HRESULT from an exception to a SocketErrorStatus enumeration value. This can be useful for handling specific network exceptions differently in your app. An app can also use the HRESULT from the exception on parameter validation errors to learn more detailed information on the error that caused the exception.

For more information on possible exceptions and how to handle exceptions, see Handling exceptions in network apps.

Using StreamSocket with Proximity, Wi-Fi Direct, and Bluetooth

Your app can use a StreamSocket for network connections between devices that are within close range. Classes in the Windows.Networking.Proximity namespace support network connections with a StreamSocket to nearby devices that use Bluetooth or Wi-Fi Direct. The PeerFinder and related classes in the Windows.Networking.Proximity namespace let your app discover another instance of your app on a nearby device. The PeerFinder.FindAllPeersAsync method browses for peer computers that are running the same app within wireless range. The PeerFinder.ConnectAsync method returns a connected StreamSocket that your app can use to transfer network data with the nearby peer app. For more information, see Supporting proximity and tapping, Windows.Networking.Proximity, PeerFinder, and the Proximity sample.

Your app can also use a StreamSocket for network connections between devices that use Wi-Fi Direct with classes in the Windows.Devices.WiFiDirect namespace. The WiFiDirectDevice class can be used to locate other devices that have a Wi-Fi Direct (WFD) capable device. The WiFiDirectDevice.GetDeviceSelector method gets the device identifier for a nearby WFD device. Once you have a reference to a nearby WFD device, you can call the WiFiDirectDevice.GetConnectionEndpointPairs method to get an EndpointPair object. The ConnectAsync(EndpointPair) or ConnectAsync(EndpointPair, SocketProtectionLevel) method on the StreamSocket class can then be used to establish a socket connection. For more information, see Windows.Devices.WiFiDirect and WiFiDirectDevice.

Bluetooth uses Bluetooth Service IDs as endpoints for StreamSocket connections, not hostnames or IP addresses. To use a StreamSocket with Bluetooth, the bluetooth.rfcomm device capability must be set in the app manifest. For more information, see the Windows.Devices.Bluetooth.Rfcomm namespace, How to specify device capabilities for Bluetooth, and the Bluetooth Rfcomm Chat sample.

Using StreamSocket on Windows Server 2012

On Windows Server 2012 and Windows Server 2012 R2, the Windows.Networking.dll that implements most of the classes in the Windows.Networking.Sockets namespace will fail to load unless the Media Foundation feature is enabled. As a result, apps that use StreamSocket and related socket classes in the Windows.Networking.Sockets namespace will fail if the Media Foundation feature is disabled. Windows Server 2012 or Windows Server 2012 R2 installs with the Media Foundation feature disabled.

The Media Foundation feature can be enabled on Windows Server 2012 or Windows Server 2012 R2 using Server Manager or by entering the following text in a command prompt or a script:

dism /online /enable-feature /featurename:ServerMediaFoundation After the Media Foundation feature is enabled, the user is prompted to restart. Once the computer is restarted, classes for sockets and WebSockets in the Windows.Networking.Sockets namespace will work as expected.

Resolving DNS service records using StreamSocket

An app can communicate with the target DNS address that belongs to a SRV record. For example, an extensible Messaging and Presence Protocol (XMPP) service in the Contoso domain corresponds to _xmpp-client._tcp.contoso.com. That service name corresponds to a server DNS name, for example, xmpp-client01.contoso.com.

To connect to the DNS address for the server for that service, use the following method call on a StreamSocket instance:

using Windows.Networking.Sockets;

StreamSocket socket = new StreamSocket();
socket.ConnectAsync(new HostName("contoso.com"), "xmpp-client");

The protocol is inferred to be TCP for StreamSocket instances. The method deals with the underscore characters.

A DNS can be configured to have an SRV hierarchy. A DNS SRV resource records could have the following form: _xmpp-client._service01._tcp.contoso.com. For this example, use the following method call on a StreamSocket instance:

socket.ConnectAsync(new HostName("contoso.com"), "xmpp-client._service01");

These code snippets use ConnectAsync. The GetEndpointPairsAsync method supports similar usage to connect to services.

Version history

Windows version SDK version Value added
1607 14393 GetEndpointPairsAsync(HostName,String)
1607 14393 GetEndpointPairsAsync(HostName,String,HostNameSortOptions)

Constructors

StreamSocket()

Creates a new StreamSocket object.

Properties

Control

Gets socket control data on a StreamSocket object.

Information

Gets socket information on a StreamSocket object.

InputStream

Gets the input stream to read from the remote destination on a StreamSocket object.

OutputStream

Gets the output stream to write to the remote host on a StreamSocket object.

Methods

CancelIOAsync()

Cancels pending reads and writes over a StreamSocket object.

Close()

Closes the StreamSocket object.

ConnectAsync(EndpointPair, SocketProtectionLevel)

Starts an asynchronous operation on a StreamSocket object to connect to a remote network destination specified as an EndpointPair object and a SocketProtectionLevel enumeration. This method is not callable from JavaScript.

ConnectAsync(EndpointPair)

Starts an asynchronous operation on a StreamSocket object to connect to a remote network destination specified as an EndpointPair object.

ConnectAsync(HostName, String, SocketProtectionLevel, NetworkAdapter)

Starts an asynchronous operation on a StreamSocket object on a specified local network adapter to connect to a remote destination specified by a remote hostname, a remote service name, and a SocketProtectionLevel.

ConnectAsync(HostName, String, SocketProtectionLevel)

Starts an asynchronous operation on a StreamSocket object to connect to a remote destination specified by a remote hostname, a remote service name, and a SocketProtectionLevel.

ConnectAsync(HostName, String)

Starts an asynchronous operation on a StreamSocket object to connect to a remote network destination specified by a remote hostname and a remote service name.

Dispose()

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

EnableTransferOwnership(Guid, SocketActivityConnectedStandbyAction)

Enables or disables the ability of your app's background task to be triggered by the socket broker when traffic for this StreamSocket arrives while the system is in connected standby.

EnableTransferOwnership(Guid)

Enables your app's background task to be triggered by the socket broker when traffic for this StreamSocket arrives while the app is not active.

GetEndpointPairsAsync(HostName, String, HostNameSortOptions)

Gets a list of EndpointPair objects based on a remote hostname and remote service name and the sort order to be used.

GetEndpointPairsAsync(HostName, String)

Gets a list of EndpointPair objects based on a remote hostname and remote service name that can be used to send TCP packets to a remote network destination.

TransferOwnership(String, SocketActivityContext, TimeSpan)

Transfers ownership of the StreamSocket to the socket brokering service, which monitors socket activity and notifies the app through a background task if there is any activity. Specifies a new SocketActivityContext and a keep alive time for the socket.

TransferOwnership(String, SocketActivityContext)

Transfers ownership of the StreamSocket to the socket brokering service, which monitors socket activity and notifies the app through a background task if there is any activity. Specifies a new SocketActivityContext for the socket.

TransferOwnership(String)

Transfers ownership of the StreamSocket to the socket brokering service, which monitors socket activity and notifies the app through a background task if there is any activity.

UpgradeToSslAsync(SocketProtectionLevel, HostName)

Starts an asynchronous operation to upgrade a connected socket to use SSL on a StreamSocket object.

Applies to

See also