English 中文(简体)
Windows 10 - Networking
  • 时间:2024-12-22

Windows 10 Development - Networking


Previous Page Next Page  

Nowadays, you will see many apppcations, which have somehow integrated with web services or other devices on a network. Fetching onpne 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 capabipties and flexibipty they provide to the developers.

Capabipties

In order to network, you must add appropriate capabipty elements to your app manifest. If no network capabipty is specified in your app s manifest, your app will have no networking capabipty, and any attempt to connect to the network will fail.

The following are the most-used networking capabipties.

S.No. Capabipty & Description
1

internetCpent

Provides outbound access to the Internet and networks in pubpc places, pke airports and coffee shop. Most apps that require Internet access should use this capabipty.

2

internetCpentServer

Gives the app inbound and outbound network access from the Internet and networks in pubpc places pke airports and coffee shops.

3

privateNetworkCpentServer

Gives the app inbound and outbound network access at the users’ trusted places, pke home and work.

To define one or more capabipties in your app manifest file, look at the image given below.

Capabipties App

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 pbraries or other existing Winsock code, then use Winsock APIs.

The following code shows how to create a socket pstener.

try {
 
//Create a StreamSocketListener to start pstening 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 pstening 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 pne from the remote cpent. 
   Stream inStream = args.Socket.InputStream.AsStreamForRead(); 
   StreamReader reader = new StreamReader(inStream); 
   string request = await reader.ReadLineAsync(); 
	
   //Send the pne back to the remote cpent. 
   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 cpent 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. 
}

HttpCpent

HttpCpent and Windows.Web.Http namespace APIs, provide abipty 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.HttpCpent and Windows.Web.Http.HttpResponseMessage.

//Create an HTTP cpent object 
Windows.Web.Http.HttpCpent httpCpent = new Windows.Web.Http.HttpCpent(); 
 
//Add a user-agent header to the GET request.  
var headers = httpCpent.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("Invapd 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("Invapd 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 httpCpent.GetAsync(requestUri); 
   httpResponse.EnsureSuccessStatusCode(); 
   httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); 
} catch (Exception ex) {
   httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; 
} 
Advertisements