Supports network communication using a stream socket over TCP or Bluetooth RFCOMM in UWP apps.
public : sealed class StreamSocket : IClosable
struct winrt::Windows::Networking::Sockets::StreamSocket : IClosable
public sealed class StreamSocket : IDisposable
Public NotInheritable Class StreamSocket Implements IDisposable
var streamSocket = new streamSocket();
Windows 10 requirements
Windows 10 (introduced v10.0.10240.0)
Windows.Foundation.UniversalApiContract (introduced v1)
bluetooth.rfcomm ID_CAP_NETWORKING [Windows Phone] privateNetworkClientServer internetClient
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.
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.
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 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.
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.
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
That service name corresponds to a server DNS name, for example,
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:
For this example, use the following method call on a StreamSocket instance:
socket.ConnectAsync(new HostName("contoso.com"), "xmpp-client._service01");
|Windows version||SDK version||Value added|
|StreamSocket() StreamSocket() StreamSocket() StreamSocket() StreamSocket()||
Creates a new StreamSocket object.
|Control Control Control Control Control||
Gets socket control data on a StreamSocket object.
|Information Information Information Information Information||
Gets socket information on a StreamSocket object.
|InputStream InputStream InputStream InputStream InputStream||
Gets the input stream to read from the remote destination on a StreamSocket object.
|OutputStream OutputStream OutputStream OutputStream OutputStream||
Gets the output stream to write to the remote host on a StreamSocket object.
- Connecting with sockets (HTML)
- Connecting with sockets (XAML)
- Handling exceptions in network apps
- How to connect with a stream socket (HTML)
- How to connect with a stream socket (XAML)
- How to secure socket connections with TLS/SSL (HTML)
- How to secure socket connections with TLS/SSL (XAML)
- How to set background connectivity options
- How to specify device capabilities for Bluetooth
- How to use advanced socket controls (HTML)
- How to use advanced socket controls (XAML)
- Supporting proximity and tapping
- Troubleshoot and debug network connections
- StreamSocketControl StreamSocketControl StreamSocketControl
- Bluetooth Rfcomm Chat sample
- ControlChannelTrigger StreamSocket sample
- Proximity sample
- StreamSocket sample (Windows 8)
- StreamSocket sample (Windows 10)
- DatagramSocket sample (Windows 10)
- Socket activity trigger stream socket sample
Send feedback about: