Supports network communication using a stream socket over TCP or Bluetooth RFCOMM in Windows Store apps.
var streamSocket = new Windows.Networking.Sockets.StreamSocket();
public sealed class StreamSocket : IDisposable
Public NotInheritable Class StreamSocket Implements IDisposable
public ref class StreamSocket sealed : IClosable
The StreamSocket class has these types of members:
The StreamSocket class has these constructors.
|StreamSocket||Creates a new StreamSocket object.|
The StreamSocket class has these methods. With C#, Visual Basic, and C++, it also inherits methods from the Object class.
|CancelIOAsync||Cancels pending reads and writes over a StreamSocket object.|
|Close||Closes the StreamSocket object.|
|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)||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.|
|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,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.|
|Dispose||Performs tasks associated with freeing, releasing, or resetting unmanaged resources.|
|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.|
|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.|
|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.|
|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,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.|
|UpgradeToSslAsync||Starts an asynchronous operation to upgrade a connected socket to use SSL on a StreamSocket object.|
The StreamSocket class has these properties.
|Read-only||Gets socket control data on a StreamSocket object.|
|Read-only||Gets socket information on a StreamSocket object.|
|Read-only||Gets the input stream to read from the remote destination on a StreamSocket object.|
|Read-only||Gets the output stream to write to the remote host on a StreamSocket object.|
The StreamSocket class supports network communications that use a stream socket over TCP or Bluetooth RFCOMM in Windows Store 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.
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.
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.
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.
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.
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.
Requirements (Windows 10 device family)
Requirements (Windows 8.x and Windows Phone 8.x)
Minimum supported client
|Windows 8 [Windows Store apps, desktop apps]|
Minimum supported server
|Windows Server 2012 [Windows Store apps, desktop apps]|
Minimum supported phone
|Windows Phone 8|
- [ DualApiPartition()]
- [ MarshalingBehavior(Agile)]
- [ Threading(Both)]
- [ Version(0x06020000)]
- Other resources
- 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
- Bluetooth Rfcomm Chat sample
- ControlChannelTrigger StreamSocket sample
- Proximity sample
- StreamSocket sample