Stream​Socket Stream​Socket Stream​Socket Class

Definition

Supports network communication using a stream socket over TCP or Bluetooth RFCOMM in Windows Store app.

public sealed class StreamSocket : IClosable, IStreamSocket, IStreamSocket2, IStreamSocket3public sealed class StreamSocket : IDisposable, IStreamSocket, IStreamSocket2, IStreamSocket3Public NotInheritable Class StreamSocket Implements IDisposable, IStreamSocket, IStreamSocket2, IStreamSocket3
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
bluetooth.rfcomm ID_CAP_NETWORKING [Windows Phone] privateNetworkClientServer internetClient

Remarks

The StreamSocket class supports network communications that use a stream socket over TCP or Bluetooth RFCOMM in Windows Store app.

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 Windows Store app 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 (e.g., the app crashes); or an abnormal connection failure is detected by the networking stack (e.g., 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 Windows Store 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 Windows Store 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 Store 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 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:ServerMediaFoundationAfter 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.

Constructors

StreamSocket() StreamSocket() StreamSocket()

Creates a new StreamSocket object.

public StreamSocket()public StreamSocket()Public Sub New()
Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_NETWORKING [Windows Phone]

Properties

Control Control Control

Gets socket control data on a StreamSocket object.

public StreamSocketControl Control { get; }public StreamSocketControl Control { get; }Public ReadOnly Property Control As StreamSocketControl
Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_NETWORKING [Windows Phone]

Remarks

The Control property gets the StreamSocketControl instance associated with a StreamSocket object.

A StreamSocketControl object is automatically created with the parent StreamSocket object. The StreamSocketControl instance can then be used to get or set control data used by the StreamSocket object. These properties on the StreamSocketControl instance include the following:

Any changes to the property values on the StreamSocketControl must be set before the StreamSocket is connected. As a result if you need to make changes to the IgnorableServerCertificateErrors, KeepAlive, NoDelay, OutboundBufferSizeInBytes , OutboundUnicastHopLimit, or QualityOfService properties, then these changes must occur before a successful call to one of the ConnectAsync methods on the StreamSocket.

See Also

Information Information Information

Gets socket information on a StreamSocket object.

public StreamSocketInformation Information { get; }public StreamSocketInformation Information { get; }Public ReadOnly Property Information As StreamSocketInformation
Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_NETWORKING [Windows Phone]

InputStream InputStream InputStream

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

public IInputStream InputStream { get; }public IInputStream InputStream { get; }Public ReadOnly Property InputStream As IInputStream
Value
IInputStream IInputStream IInputStream

A sequential stream of bytes to be read from the remote destination.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_NETWORKING [Windows Phone]

Remarks

This property can be used to read incoming data received from the remote network destination on a socket object. Incoming data can be read using the IInputStream.ReadAsync method directly or by passing the IInputStream object to other objects (DataReader, for example) that accept an IInputStream as a parameter.

OutputStream OutputStream OutputStream

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

public IOutputStream OutputStream { get; }public IOutputStream OutputStream { get; }Public ReadOnly Property OutputStream As IOutputStream
Value
IOutputStream IOutputStream IOutputStream

A sequential stream of bytes to be written to the remote destination.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_NETWORKING [Windows Phone]

Remarks

This property can be used to write outgoing data to be sent to the remote network destination on a socket object. Outgoing data can be written using the IOutputStream.WriteAsync method directly or by passing the IOutputStream object to other objects (DataWriter, for example) that accept an IOutputStream as a parameter.

Methods

CancelIOAsync() CancelIOAsync() CancelIOAsync()

Cancels pending reads and writes over a StreamSocket object.

public IAsyncAction CancelIOAsync()public IAsyncAction CancelIOAsync()Public Function CancelIOAsync() As IAsyncAction
Returns

An asynchronous cancel operation on a StreamSocket object.

Attributes

Remarks

Call CancelIOAsync to cancel any pending reads or writes on this socket before you call TransferOwnership when your app is about to be suspended.

CancelIOAsync does not guarantee that all read/write completion handlers have finished executing before it signals completion. It does, however, guarantee that all I/O operations will have reached a terminal state (either Completed or Error) by the time it signals completion. If your app needs to wait for all pending I/O operation handlers to finish executing, you must implement your own app-level sychronization logic. The Socket Activity Stream Socket sample demonstrates one way to do this.

Note

CancelIOAsync cancels pending writes and reads in the Windows Runtime, but if there is a write buffer pending in networking drivers, it flushes the write.

Close() Close() Close()

Closes the StreamSocket object.

public void Close()This member is not implemented in C#This member is not implemented in VB.Net
Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_NETWORKING [Windows Phone]

Remarks

The Close method aborts any pending operations and releases all unmanaged resources associated with the StreamSocket object. Aborting pending read operations on an InputStream or aborting pending write operations on an OutputStream will also result in the StreamSocket object being closed.

The Close is used by Windows Store app s 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.

ConnectAsync(EndpointPair) ConnectAsync(EndpointPair) ConnectAsync(EndpointPair)

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

public IAsyncAction ConnectAsync(EndpointPair endpointPair)public IAsyncAction ConnectAsync(EndpointPair endpointPair)Public Function ConnectAsync(endpointPair As EndpointPair) As IAsyncAction
Parameters
endpointPair
EndpointPair EndpointPair EndpointPair

An EndpointPair object that specifies the local hostname or IP address, the local service name or TCP port, the remote hostname or remote IP address, and the remote service name or remote TCP port for the remote network destination.

Returns

An asynchronous connect operation on a StreamSocket object.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_NETWORKING [Windows Phone] privateNetworkClientServer internetClientServer

Remarks

If the EndpointPair object passed in the endpointPair parameter contains null for the LocalHostName property, then the system will supply the local IP address that will be used. If the EndpointPair object passed in the endpointPair parameter contains an empty string for the LocalServiceName property, then the system will supply the local TCP port that will be used.

In a Windows Store 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. Connecting through proxies is not supported when a local host address is specified, so the LocalHostName property passed in the endpointPair parameter must be null. For more detailed information, see the remarks on Support for proxies in the StreamSocket class reference.

In a Windows Phone Store app, the StreamSocket class does not provide automatic support for proxies.

ConnectAsync(EndpointPair, SocketProtectionLevel) ConnectAsync(EndpointPair, SocketProtectionLevel) 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.

public IAsyncAction ConnectAsync(EndpointPair endpointPair, SocketProtectionLevel protectionLevel)public IAsyncAction ConnectAsync(EndpointPair endpointPair, SocketProtectionLevel protectionLevel)Public Function ConnectAsync(endpointPair As EndpointPair, protectionLevel As SocketProtectionLevel) As IAsyncAction
Parameters
endpointPair
EndpointPair EndpointPair EndpointPair

An EndpointPair object that specifies local hostname or IP address, local service name or TCP port, the remote hostname or remote IP address, and the remote service name or remote TCP port for the remote network destination.

protectionLevel
SocketProtectionLevel SocketProtectionLevel SocketProtectionLevel

The protection level that represents the integrity and encryption for a StreamSocket object.

Returns

An asynchronous connect operation on a StreamSocket object.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_NETWORKING [Windows Phone] privateNetworkClientServer internetClientServer

Remarks

If the EndpointPair object passed in the endpointPair parameter contains null for the LocalHostName property, then the system will supply the local IP address that will be used. If the EndpointPair object passed in the endpointPair parameter contains an empty string for the LocalServiceName property, then the system will supply the local TCP port that will be used.

If the EndpointPair object passed in the endpointPair parameter contains null for the LocalServiceName property, then an error will occur.

The ConnectAsync(EndpointPair, SocketProtectionLevel) method is not exposed in JavaScript. This method can't be called from JavaScript since it has the same number of arguments as the ConnectAsync(HostName, String) method.

Apps written in JavaScript can't connect a StreamSocket using an EndpointPair using SSL directly. In order to connect an EndpointPair using SSL, JavaScript apps can use the following code instead.


var clientSocket = new Windows.Networking.Sockets.StreamSocket();
var remoteName = new Windows.Networking.HostName("www.contoso.com");
var myEndpointPair = EndpointPair();

// Set properties needed on the EndpointPair
// We only set remote properties and the localServiceName,
// But the localHostName could also be set

myEndpointPair.localServiceName = "12345";
myEndpointPair.remoteHostName = remoteName;
myEndpointPair.remoteServiceName = "http";

// First connect the socket without SSL
clientSocket.connectAsync(myEendpointPair>).then(function () {
    // Now upgrade the connection to SSL
    clientSocket.upgradeToSslAsync(SocketProtectionLevel.Ssl).then(function () {
        // now connected using SSL
    }
}   

When the protectionLevel parameter is set to a value that requires SSL or TLS, the socket connect operation may not timeout if the remote endpoint does not support SSL or TLS. This can occur if initial connect operation succeeds but the remote endpoint does not terminate the connection during the SSL handshake. To protect against this situation, an app should set a timeout on the connect operation when requesting SSL/TLS and abort the operation if the timeout expires. For more information on setting a timeout using JavaScript on socket operations, see How to set timeouts on socket operations . For more information on setting a timeout using VB, C#, or C++ on socket operations, see How to set timeouts on socket operations .

In a Windows Store 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. Connecting through proxies is not supported when a local host address is specified, so the LocalHostName property passed in the endpointPair parameter must be null. For more detailed information, see the remarks on Support for proxies in the StreamSocket class reference.

In a Windows Phone Store app, the StreamSocket class does not provide automatic support for proxies.

ConnectAsync(HostName, String) ConnectAsync(HostName, String) 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.

public IAsyncAction ConnectAsync(HostName remoteHostName, String remoteServiceName)public IAsyncAction ConnectAsync(HostName remoteHostName, String remoteServiceName)Public Function ConnectAsync(remoteHostName As HostName, remoteServiceName As String) As IAsyncAction
Parameters
remoteHostName
HostName HostName HostName

The hostname or IP address of the remote network destination. For Bluetooth RFCOMM, this is a MAC address.

remoteServiceName
System.String System.String System.String

The service name or TCP port number of the remote network destination. For Bluetooth RFCOMM, this is the Bluetooth address.

Returns

An asynchronous connect operation on a StreamSocket object.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_NETWORKING [Windows Phone] privateNetworkClientServer internetClientServer

Remarks

The remoteHostName and remoteServiceName parameters must be provided. If the remoteHostName is null or the remoteServiceName is null or an empty string, an error will occur.

In a Windows Store 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. For more detailed information, see the remarks on Support for proxies in the StreamSocket class reference.

In a Windows Phone Store app, the StreamSocket class does not provide automatic support for proxies.

ConnectAsync(HostName, String, SocketProtectionLevel) ConnectAsync(HostName, String, 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.

public IAsyncAction ConnectAsync(HostName remoteHostName, String remoteServiceName, SocketProtectionLevel protectionLevel)public IAsyncAction ConnectAsync(HostName remoteHostName, String remoteServiceName, SocketProtectionLevel protectionLevel)Public Function ConnectAsync(remoteHostName As HostName, remoteServiceName As String, protectionLevel As SocketProtectionLevel) As IAsyncAction
Parameters
remoteHostName
HostName HostName HostName

The hostname or IP address of the remote network destination. For Bluetooth RFCOMM, this is a MAC address.

remoteServiceName
System.String System.String System.String

The service name or TCP port number of the remote network destination. For Bluetooth RFCOMM, this is the Bluetooth address.

protectionLevel
SocketProtectionLevel SocketProtectionLevel SocketProtectionLevel

The protection level that represents the integrity and encryption for the StreamSocket object.

Returns

An asynchronous connect operation on a StreamSocket object.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_NETWORKING [Windows Phone] privateNetworkClientServer internetClientServer

Remarks

The remoteHostName and remoteServiceName parameters must be provided. If the remoteHostName is null or the remoteServiceName is null or an empty string, an error will occur.

When the protectionLevel parameter is set to a value that requires SSL or TLS, the socket connect operation may not timeout if the remote network destination does not support SSL or TLS. This can occur if initial connect operation succeeds but the remote host does not terminate the connection during the SSL handshake. To protect against this situation, an app should set a timeout on the connect operation when requesting SSL/TLS and abort the operation if the timeout expires. For more information on setting a timeout using JavaScript on socket operations, see How to set timeouts on socket operations . For more information on setting a timeout using VB, C#, or C++ on socket operations, see How to set timeouts on socket operations .

In a Windows Store 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. For more detailed information, see the remarks on Support for proxies in the StreamSocket class reference.

In a Windows Phone Store app, the StreamSocket class does not provide automatic support for proxies.

ConnectAsync(HostName, String, SocketProtectionLevel, NetworkAdapter) ConnectAsync(HostName, String, SocketProtectionLevel, NetworkAdapter) 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.

public IAsyncAction ConnectAsync(HostName remoteHostName, String remoteServiceName, SocketProtectionLevel protectionLevel, NetworkAdapter adapter)public IAsyncAction ConnectAsync(HostName remoteHostName, String remoteServiceName, SocketProtectionLevel protectionLevel, NetworkAdapter adapter)Public Function ConnectAsync(remoteHostName As HostName, remoteServiceName As String, protectionLevel As SocketProtectionLevel, adapter As NetworkAdapter) As IAsyncAction
Parameters
remoteHostName
HostName HostName HostName

The hostname or IP address of the remote network destination. For Bluetooth RFCOMM, this is a MAC address.

remoteServiceName
System.String System.String System.String

The service name or TCP port number of the remote network destination. For Bluetooth RFCOMM, this is the Bluetooth address.

protectionLevel
SocketProtectionLevel SocketProtectionLevel SocketProtectionLevel

The protection level that represents the integrity and encryption for the StreamSocket object.

adapter
NetworkAdapter NetworkAdapter NetworkAdapter

The local network adapter to use for the connect operation on the StreamSocket object.

Returns

An asynchronous connect operation on a StreamSocket object.

Attributes

Remarks

The ConnectAsync(Hostname, String, SocketProtectionLevel, NetworkAdapter) method binds to a network interface specified in the adapter parameter on the local computer and the remote hostname and service name specified in the remoteHostName and remoteServiceName parameters with the protection level specified in the protectionLevel parameter.

The remoteHostName and remoteServiceName parameters must be provided. If the remoteHostName is null or the remoteServiceName is null or an empty string, an error will occur. If the adapter parameter is null, an error will occur.

The name resolution mechanism used by the ConnectAsync(Hostname, String, SocketProtectionLevel, NetworkAdapter) method is limited to the specified interface for the domain name system (DNS) namespace.

Using the specified network adapter is on a best-effort basis. Systems with adapters configured in weak-host or forwarding modes may use an adapter other than the specified adapter.

When the protectionLevel parameter is set to a value that requires SSL or TLS, the socket connect operation may not timeout if the remote network destination does not support SSL or TLS. This can occur if initial connect operation succeeds but the remote host does not terminate the connection during the SSL handshake. To protect against this situation, an app should set a timeout on the connect operation when requesting SSL/TLS and abort the operation if the timeout expires. For more information on setting a timeout using JavaScript on socket operations, see How to set timeouts on socket operations . For more information on setting a timeout using VB, C#, or C++ on socket operations, see How to set timeouts on socket operations .

An app can retrieve a valid NetworkAdapter by inspecting a HostName instance (using the NetworkInformation.GetHostNames method, for example) and retrieving the IPInformation object from the Hostname.IPInformation property. The IPInformation.NetworkAdapter property can be used to retrieve the associated NetworkAdapter.

In a Windows Store 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. However, connecting through proxies is not supported when a specific network adapter is selected. So proxy support is disabled when the ConnectAsync(HostName, String, SocketProtectionLevel, NetworkAdapter) method is used. For more detailed information, see the remarks on Support for proxies in the StreamSocket class reference.

In a Windows Phone Store app, the StreamSocket class does not provide automatic support for proxies.

Dispose() Dispose() Dispose()

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

This member is not implemented in C++void Dispose()Sub Dispose
Attributes

EnableTransferOwnership(Guid) EnableTransferOwnership(Guid) 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.

public void EnableTransferOwnership(Guid taskId)public void EnableTransferOwnership(Guid taskId)Public Function EnableTransferOwnership(taskId As Guid) As void
Parameters
taskId
System.Guid System.Guid System.Guid

The IBackgroundTaskRegistration.TaskId of the background task that will be triggered by the socket broker when traffic arrives for this StreamSocket.

Attributes

EnableTransferOwnership(Guid, SocketActivityConnectedStandbyAction) EnableTransferOwnership(Guid, SocketActivityConnectedStandbyAction) 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.

public void EnableTransferOwnership(Guid taskId, SocketActivityConnectedStandbyAction connectedStandbyAction)public void EnableTransferOwnership(Guid taskId, SocketActivityConnectedStandbyAction connectedStandbyAction)Public Function EnableTransferOwnership(taskId As Guid, connectedStandbyAction As SocketActivityConnectedStandbyAction) As void
Parameters
taskId
System.Guid System.Guid System.Guid

The IBackgroundTaskRegistration.TaskId of the background task being enabled or disabled.

connectedStandbyAction
SocketActivityConnectedStandbyAction SocketActivityConnectedStandbyAction SocketActivityConnectedStandbyAction

Specifies whether to enable or disable the activation of the background task when traffic arrives.

Attributes

GetEndpointPairsAsync(HostName, String) GetEndpointPairsAsync(HostName, String) 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.

public static IAsyncOperation<IVectorView<EndpointPair>> GetEndpointPairsAsync(HostName remoteHostName, String remoteServiceName)public static IAsyncOperation<IVectorView<EndpointPair>> GetEndpointPairsAsync(HostName remoteHostName, String remoteServiceName)Public Static Function GetEndpointPairsAsync(remoteHostName As HostName, remoteServiceName As String) As IAsyncOperation( Of IVectorViewEndpointPair )
Parameters
remoteHostName
HostName HostName HostName

The hostname of a service. The service might actually be hosted on multiple services, so that a DNS lookup returns multiple IP addresses for the various servers. This method returns one endpoint pair for each of the servers found by a DNS lookup.

remoteServiceName
System.String System.String System.String

The name or port number of a remote service. Note that different servers might support the named service on different physical ports, so not all of the returned endpoints will use the same service port number.

Returns

An asynchronous lookup operation. On successful completion, the returned list contains one EndpointPair for each remote host found, with one end point being one of the remote hosts and the other being the local host.

Attributes
Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)
Capabilities
bluetooth.rfcomm ID_CAP_NETWORKING [Windows Phone] privateNetworkClientServer internetClient

Remarks

This method gets a list of possible EndpointPair objects that can be used by a StreamSocket to send data to a remote network destination using TCP. The returned list is sorted so that the address pairs that are best suited for communication between two peers occur earlier in the list.

A StreamSocket can use the list returned by this method to try and bind or connect to each EndpointPair object until a connection can be made. An EndpointPair object from the list would be used with the ConnectAsync(EndpointPair) methods

GetEndpointPairsAsync(HostName, String, HostNameSortOptions) GetEndpointPairsAsync(HostName, String, HostNameSortOptions) 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.

public static IAsyncOperation<IVectorView<EndpointPair>> GetEndpointPairsAsync(HostName remoteHostName, String remoteServiceName, HostNameSortOptions sortOptions)public static IAsyncOperation<IVectorView<EndpointPair>> GetEndpointPairsAsync(HostName remoteHostName, String remoteServiceName, HostNameSortOptions sortOptions)Public Static Function GetEndpointPairsAsync(remoteHostName As HostName, remoteServiceName As String, sortOptions As HostNameSortOptions) As IAsyncOperation( Of IVectorViewEndpointPair )
Parameters
remoteHostName
HostName HostName HostName

The remote hostname or IP address.

remoteServiceName
System.String System.String System.String

The remote service name or UDP port.

sortOptions
HostNameSortOptions HostNameSortOptions HostNameSortOptions

The sort order to use when returning the list.

Returns

A list of EndpointPair objects.

Attributes
Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)
Capabilities
bluetooth.rfcomm ID_CAP_NETWORKING [Windows Phone] privateNetworkClientServer internetClient

Remarks

The GetEndpointPairsAsync method gets a list of possible EndpointPair objects that can be used by a StreamSocket to connect to a remote network destination. The returned list is sorted based on the sortOptions parameter.

A StreamSocket can use the list returned by this method to try and bind or connect to each EndpointPair object until a remote destination can be reached. An EndpointPair object from the list would be used with the ConnectAsync(EndpointPair) method.

TransferOwnership(String) TransferOwnership(String) 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.

public void TransferOwnership(String socketId)public void TransferOwnership(String socketId)Public Function TransferOwnership(socketId As String) As void
Parameters
socketId
System.String System.String System.String

A string the app uses to identify the transferred socket. The string should identify this socket uniquely within the app. When activity occurs on this socket, this string will be provided to the app to identify the socket.

Attributes

Remarks

Your app should call this method to transfer ownership of the StreamSocket to the socket brokering service when the app is about to be suspended, or at the end of a background task. Your app should not access the StreamSocket object after calling this method, except when responding to notifications from the socket brokering service.

Note

This call fails if there is any pending I/O on the StreamSocket. Your code should call StreamSocket.CancelIOAsync to cancel any further new traffic, then handle all pending traffic, and then update the SocketActivityContext, before calling StreamSocket.TransferOwnership.

TransferOwnership(String, SocketActivityContext) TransferOwnership(String, SocketActivityContext) 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.

public void TransferOwnership(String socketId, SocketActivityContext data)public void TransferOwnership(String socketId, SocketActivityContext data)Public Function TransferOwnership(socketId As String, data As SocketActivityContext) As void
Parameters
socketId
System.String System.String System.String

A string the app uses to identify the transferred socket. The string should identify this socket uniquely within the app. When activity occurs on this socket, this string will be provided to the app to identify the socket.

data
SocketActivityContext SocketActivityContext SocketActivityContext

Use the SocketActivityContext to pass context information through the socket broker. When your app is notified by the broker of activity, this SocketActivityContext will be provided to your app to help establish the context in which you should handle the notification.

Attributes

Remarks

Your app should call this method to transfer ownership of the StreamSocket to the socket brokering service when the app is about to be suspended, or at the end of a background task. Your app should not access the StreamSocket object after calling this method, except when responding to notifications from the socket brokering service.

Note

This call fails if there is any pending I/O on the StreamSocket. Your code should call StreamSocket.CancelIOAsync to cancel any further new traffic, then handle all pending traffic, and then update the SocketActivityContext, before calling StreamSocket.TransferOwnership.

TransferOwnership(String, SocketActivityContext, TimeSpan) TransferOwnership(String, SocketActivityContext, TimeSpan) 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.

public void TransferOwnership(String socketId, SocketActivityContext data, TimeSpan keepAliveTime)public void TransferOwnership(String socketId, SocketActivityContext data, TimeSpan keepAliveTime)Public Function TransferOwnership(socketId As String, data As SocketActivityContext, keepAliveTime As TimeSpan) As void
Parameters
socketId
System.String System.String System.String

A string the app uses to identify the transferred socket. The string should identify this socket uniquely within the app. When activity occurs on this socket, this string will be provided to the app to identify the socket.

data
SocketActivityContext SocketActivityContext SocketActivityContext

Use the SocketActivityContext to pass context information through the socket broker. When your app is notified by the broker of activity, this SocketActivityContext will be provided to your app to help establish the context in which you should handle the notification.

keepAliveTime
TimeSpan TimeSpan TimeSpan

How long the socket brokering service should monitor the socket for activity.

Attributes

Remarks

Your app should call this method to transfer ownership of the StreamSocket to the socket brokering service when the app is about to be suspended, or at the end of a background task. Your app should not access the StreamSocket object after calling this method, except when responding to notifications from the socket brokering service.

Note

This call fails if there is any pending I/O on the StreamSocket. Your code should call StreamSocket.CancelIOAsync to cancel any further new traffic, then handle all pending traffic, and then update the SocketActivityContext, before calling StreamSocket.TransferOwnership.

UpgradeToSslAsync(SocketProtectionLevel, HostName) UpgradeToSslAsync(SocketProtectionLevel, HostName) UpgradeToSslAsync(SocketProtectionLevel, HostName)

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

public IAsyncAction UpgradeToSslAsync(SocketProtectionLevel protectionLevel, HostName validationHostName)public IAsyncAction UpgradeToSslAsync(SocketProtectionLevel protectionLevel, HostName validationHostName)Public Function UpgradeToSslAsync(protectionLevel As SocketProtectionLevel, validationHostName As HostName) As IAsyncAction
Parameters
protectionLevel
SocketProtectionLevel SocketProtectionLevel SocketProtectionLevel

The protection level that represents the integrity and encryption on the StreamSocket object.

validationHostName
HostName HostName HostName

The hostname of the remote network destination that is used for validation when upgrading to SSL.

Returns

An asynchronous operation to upgrade to use SSL on a StreamSocket object.

Attributes
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_NETWORKING [Windows Phone]

Remarks

The UpgradeToSslAsync method can only be used to upgrade an already established connection made with a SocketProtectionLevel of PlainSocket.

The typical order of operations to establish an SSL connection is as follows:

  • Create the StreamSocket.
  • Get socket control data on a StreamSocketControl object using the Control property and set any properties before calling one of the ConnectAsync methods.
  • Call one of the ConnectAsync methods to establish a connection with the remote endpoint. If an SSL/TLS connection 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, 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 abort any pending operations and release all unmanaged resources associated with the StreamSocket object. The UpgradeToSslAsync method requires that the remote server to which the connection was established is able to upgrade a TCP connection to an SSL connection.

The UpgradeToSslAsync method can only be used for client connections. This method can't be used to upgrade a connection accepted by the StreamSocketListener to an SSL connection. The UpgradeToSslAsync method only implements the client parts of the SSL protocol negotiation, not the server parts that would be needed to listen for and accept SSL connections.

The UpgradeToSslAsync method does not support the use of client certificates.

See Also

See Also