Jaa


DatagramSocket Class

Definition

Supports network communication using a UDP datagram socket.

For a code example, see Sockets.

public ref class DatagramSocket 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 DatagramSocket 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 DatagramSocket 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 DatagramSocket : 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 DatagramSocket : System.IDisposable
function DatagramSocket()
Public NotInheritable Class DatagramSocket
Implements IDisposable
Inheritance
Object Platform::Object IInspectable DatagramSocket
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
ID_CAP_NETWORKING [Windows Phone] internetClient privateNetworkClientServer

Remarks

The DatagramSocket class supports network communication using a UDP datagram socket. The DatagramSocket object can be used for client apps that send UDP packets or for server apps that listen for incoming UDP data.

Several steps are needed to send or receive data using a DatagramSocket object. Your app first assigns the MessageReceived event to an event handler. To listen for incoming packets from a remote endpoint (a server scenario, for example), your app calls either the BindEndpointAsync or BindServiceNameAsync method to bind the DatagramSocket to a local service name or UDP port. However when your app needs to communicate with a single remote endpoint (client scenario, for example), your app calls the ConnectAsync method. The MessageReceived event handler must be set before any bind or connect operation, otherwise an error will occur.

The typical order of operations is as follows:

  1. Create the DatagramSocket.
  2. Use the Control property to retrieve a DatagramSocketControl object and set any advanced controls. This step is not normally needed by most apps.
  3. Assign the MessageReceived event to an event handler.
  4. To listen for incoming packets from any remote endpoint (server scenario, for example), call the BindEndpointAsync or BindServiceNameAsync method to bind the DatagramSocket to a local service name or UDP port.
  5. To communicate with a single remote endpoint (client scenario, for example), call the ConnectAsync method to bind the DatagramSocket to a specific remote endpoint.
  6. The MessageReceived event handler will be invoked whenever a message from the remote endpoint arrives. This class can also be used to join a multicast group and send UDP packets to the multicast group. For more information, see the JoinMulticastGroup method.

Handling exceptions

You must write code to handle exceptions when you call asynchronous methods on the DatagramSocket 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 a convenient helper method and enumeration for handling errors when using sockets. 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 DatagramSocket with Wi-Fi Direct

Your app can use a DatagramSocket for network data transfers between devices that use Wi-Fi Direct using 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. Methods on the DatagramSocket class can be used to send and receive data to the EndpointPair object. For more information, see Windows.Devices.WiFiDirect and WiFiDirectDevice.

Using DatagramSocket 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 DatagramSocket 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 DatagramSocket

An app can communicate with the target DNS address that belongs to a SRV record. For example, a Simple Traversal of UDP through Network Address Translation (NAT) (STUN) service in the Contoso domain corresponds to _stun._udp.contoso.com. That service name corresponds to a server DNS name, for example, stunServer01.contoso.com.

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

using Windows.Networking.Sockets;

DatagramSocket socket = new DatagramSocket();
socket.ConnectAsync(new HostName("contoso.com"), "stun");

The protocol is inferred to be UDP for DatagramSocket 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: _stun._service01._udp.contoso.com. For this example, use the following method call on a DatagramSocket instance:

socket.ConnectAsync(new HostName("contoso.com"), "stun._service01");

These code snippets use ConnectAsync. The GetOutputStreamAsync and GetEndpointPairsAsync methods support similar usage to connect to services.

Constructors

DatagramSocket()

Creates a new DatagramSocket object.

Properties

Control

Gets socket control data on a DatagramSocket object.

Information

Gets socket information on the local and remote hostnames and local and remote service names for the DatagramSocket object.

OutputStream

Gets the output stream to write to the remote host.

Methods

BindEndpointAsync(HostName, String)

Starts a bind operation on a DatagramSocket to a local hostname and a local service name.

BindServiceNameAsync(String, NetworkAdapter)

Starts a bind operation on a DatagramSocket to a local service name and specific network interface.

BindServiceNameAsync(String)

Starts a bind operation on a DatagramSocket to a local service name.

CancelIOAsync()

Cancels pending reads and writes over a DatagramSocket object.

Close()

Closes the DatagramSocket object and aborts any pending operation on the DatagramSocket.

ConnectAsync(EndpointPair)

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

ConnectAsync(HostName, String)

Starts a connect operation on a DatagramSocket to a remote 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 your app's background task to be triggered by the socket broker when traffic for this DatagramSocket 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 DatagramSocket 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 datagrams to a remote network destination.

GetOutputStreamAsync(EndpointPair)

Starts an operation to get an IOutputStream to a remote network destination specified by an EndpointPair object that can then be used to send network data.

GetOutputStreamAsync(HostName, String)

Starts an operation to get an IOutputStream to a remote destination specified by a remote hostname and a remote service name that can then be used to send network data.

JoinMulticastGroup(HostName)

Joins a DatagramSocket object to a multicast group.

TransferOwnership(String, SocketActivityContext, TimeSpan)

Transfers ownership of the DatagramSocket 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 DatagramSocket to the socket brokering service, which monitors socket activity and notifies the app through a background task if there is any activity.

TransferOwnership(String)

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

Events

MessageReceived

An event that indicates that a message was received on the DatagramSocket object.

Applies to

See also