Networking in Universal Windows Platform (UWP) Apps
This section provides comprehensive guidance on how to implement networking capabilities in your Universal Windows Platform (UWP) applications. UWP offers a robust set of APIs that enable your apps to connect to the internet, communicate with servers, and handle various network scenarios.
Key Networking Concepts and APIs
UWP provides several core namespaces and classes for networking:
Windows.Networking: The root namespace for networking APIs.Windows.Networking.Connectivity: Provides classes for managing network connections, retrieving connection profiles, and detecting network status changes.Windows.Networking.Sockets: Offers APIs for low-level socket communication, including TCP and UDP sockets.Windows.Web.Http: A modern, asynchronous API for performing HTTP requests and responses, supporting RESTful services and web APIs.
Common Networking Tasks
1. Checking Network Connectivity
Before attempting any network operation, it's good practice to check if the device is connected to a network. The ConnectionProfile class is crucial for this.
Note on Connectivity
You can use NetworkInformation.GetInternetConnectivityStatus() to quickly determine the internet connectivity status. For more detailed information about the current connection profile (e.g., signal strength, network cost), use NetworkInformation.GetInternetConnectionProfile().
2. Performing HTTP Requests
For interacting with web services and APIs, the Windows.Web.Http namespace is recommended. It provides an asynchronous, efficient way to send GET, POST, PUT, DELETE, and other HTTP methods.
using Windows.Web.Http;
using System.Threading.Tasks;
public async Task<string> FetchDataAsync(string url)
{
using (var client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync(new Uri(url));
response.EnsureSuccessStatusCode(); // Throws if status code is not 2xx
return await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException e)
{
// Handle exceptions (e.g., network errors, invalid URL)
System.Diagnostics.Debug.WriteLine($"Error fetching data: {e.Message}");
return null;
}
}
}
3. Socket Communication (TCP/UDP)
For scenarios requiring direct low-level network communication, such as custom protocols or real-time data streams, use the Windows.Networking.Sockets namespace.
TCP Socket Example (Client)
using Windows.Networking.Sockets;
using System.Threading.Tasks;
using Windows.Storage.Streams;
public async Task ConnectAndSendTcpAsync(string hostname, string port, string message)
{
var socket = new StreamSocket();
try
{
await socket.ConnectAsync(new Windows.Networking.HostName(hostname), port);
using (var writer = new DataWriter(socket.OutputStream))
{
writer.WriteString(message);
await writer.StoreAsync();
System.Diagnostics.Debug.WriteLine("Message sent via TCP.");
}
// For receiving data, use socket.InputStream
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"TCP connection failed: {ex.Message}");
}
}
UDP Socket Example (Datagram)
using Windows.Networking.Sockets;
using System.Threading.Tasks;
using Windows.Storage.Streams;
public async Task SendUdpDatagramAsync(string hostname, string port, string message)
{
var client = new DatagramSocket();
client.MessageReceived += MessageReceivedHandler; // Optional: for receiving responses
try
{
await client.ConnectAsync(new Windows.Networking.HostName(hostname), port);
using (var writer = new DataWriter(client.OutputStream))
{
writer.WriteString(message);
await writer.StoreAsync();
System.Diagnostics.Debug.WriteLine("UDP datagram sent.");
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"UDP send failed: {ex.Message}");
}
}
private void MessageReceivedHandler(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
// Process received UDP data
using (var reader = args.GetDataReader())
{
string receivedMessage = reader.ReadString(reader.UnconsumedBufferLength);
System.Diagnostics.Debug.WriteLine($"UDP Received: {receivedMessage}");
}
}
4. Handling Background Network Operations
UWP allows your app to perform network operations even when it's not in the foreground using the BackgroundUploader and BackgroundDownloader classes. This is essential for tasks like uploading files or downloading content without requiring the user to keep the app open.
Important Considerations for Background Networking
Ensure your app declares the necessary capabilities in its manifest (e.g., Internet (Client & Server)) and handles network cost policies to avoid unexpected data charges for users.