”;
Nowadays, you will see many applications, which have somehow integrated with web services or other devices on a network. Fetching online weather content, latest news, chatting or peer-to-peer games are some examples which use network services. These apps are built using a wide variety of networking APIs. In Windows 10, the networking APIs are improved in terms of their speed and memory performances as well as the capabilities and flexibility they provide to the developers.
Capabilities
In order to network, you must add appropriate capability elements to your app manifest. If no network capability is specified in your app”s manifest, your app will have no networking capability, and any attempt to connect to the network will fail.
The following are the most-used networking capabilities.
S.No. | Capability & Description |
---|---|
1 |
internetClient Provides outbound access to the Internet and networks in public places, like airports and coffee shop. Most apps that require Internet access should use this capability. |
2 |
internetClientServer Gives the app inbound and outbound network access from the Internet and networks in public places like airports and coffee shops. |
3 |
privateNetworkClientServer Gives the app inbound and outbound network access at the users’ trusted places, like home and work. |
To define one or more capabilities in your app manifest file, look at the image given below.
The Universal Windows Platform (UWP) contains a large set of networking APIs by targeting the following −
- Querying the connectivity status of the device and connecting to the peer devices.
- Communicating with REST web services and
- Downloading large media files in the background
Networking Technologies
In Universal Windows Platform (UWP), the following networking technologies are available for the developers, which can be used in many different situations.
Sockets
Sockets are used when you want to communicate with another device with your own protocol.
-
You can use both, Windows.Networking.Sockets and Winsock to communicate with other devices as a Universal Windows Platform (UWP) app developer.
-
Windows.Networking.Sockets has the advantage of being a modern API, designed for use by UWP developers.
-
If you are using cross-platform networking libraries or other existing Winsock code, then use Winsock APIs.
The following code shows how to create a socket listener.
try { //Create a StreamSocketListener to start listening for TCP connections. Windows.Networking.Sockets.StreamSocketListener socketListener = new Windows.Networking.Sockets.StreamSocketListener(); //Hook up an event handler to call when connections are received. socketListener.ConnectionReceived += SocketListener_ConnectionReceived; //Start listening for incoming TCP connections on the specified port. You can specify any port that''s not currently in use. await socketListener.BindServiceNameAsync("1337"); } catch (Exception e) { //Handle exception. }
The following code shows the implementation of the SocketListener_ConnectionReceived event handler.
private async void SocketListener_ConnectionReceived( Windows.Networking.Sockets.StreamSocketListen er sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args){ //Read line from the remote client. Stream inStream = args.Socket.InputStream.AsStreamForRead(); StreamReader reader = new StreamReader(inStream); string request = await reader.ReadLineAsync(); //Send the line back to the remote client. Stream outStream = args.Socket.OutputStream.AsStreamForWrite(); StreamWriter writer = new StreamWriter(outStream); await writer.WriteLineAsync(request); await writer.FlushAsync(); }
WebSocket
The WebSockets protocol provides a fast and secure two-way communication between a client and a server over the web. Universal Windows Platform (UWP) developers can use the MessageWebSocket and StreamWebSocket classes to connect with servers that support the Websocket protocol.
Important features are −
-
Under the WebSocket Protocol, data is transferred immediately over a full-duplex single socket connection.
-
It allows messages to be sent and received from both endpoints in real time.
-
WebSockets are ideal for use in real-time gaming where instant social network notifications and up-to-date displays of information (game statistics) need to be secure and use fast data transfer.
The following code shows how to send and receive messages on a secure connection.
MessageWebSocket webSock = new MessageWebSocket(); //In this case we will be sending/receiving a string so we need to set the MessageType to Utf8. webSock.Control.MessageType = SocketMessageType.Utf8; //Add the MessageReceived event handler. webSock.MessageReceived += WebSock_MessageReceived; //Add the Closed event handler. webSock.Closed += WebSock_Closed; Uri serverUri = new Uri("wss://echo.websocket.org"); try { //Connect to the server. await webSock.ConnectAsync(serverUri); //Send a message to the server. await WebSock_SendMessage(webSock, "Hello, world!"); } catch (Exception ex) { //Add code here to handle any exceptions }
The following code shows the event implementation, which will receive a string from a connected WebSocket.
//The MessageReceived event handler. private void WebSock_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args){ DataReader messageReader = args.GetDataReader(); messageReader.UnicodeEncoding = UnicodeEncoding.Utf8; string messageString = messageReader.ReadString( messageReader.UnconsumedBufferLength); //Add code here to do something with the string that is received. }
HttpClient
HttpClient and Windows.Web.Http namespace APIs, provide ability to the developer to send and receive information using the HTTP 2.0 and HTTP 1.1 protocols.
It can be used to −
- communicate with a web service or a web server.
- Upload or download a number of small files.
- Stream the content over the network.
The following code shows how to send a GET request using Windows.Web.Http.HttpClient and Windows.Web.Http.HttpResponseMessage.
//Create an HTTP client object Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true, //especially if the header value is coming from user input. string header = "ie"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception("Invalid header value: " + header); } Uri requestUri = new Uri("http://www.contoso.com"); //Send the GET request asynchronously and retrieve the response as a string. Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); } catch (Exception ex) { httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; }
”;