📜  Windows 10开发-联网

📅  最后修改于: 2020-11-18 10:14:48             🧑  作者: Mango


如今,您将看到许多应用程序,它们以某种方式与网络服务或网络上的其他设备集成在一起。使用网络服务的一些示例是获取在线天气内容,最新新闻,聊天或对等游戏。这些应用程序使用多种网络API构建。在Windows 10中,网络API在速度和内存性能以及为开发人员提供的功能和灵活性方面得到了改进。

能力

为了联网,必须将适当的功能元素添加到您的应用清单中。如果您的应用清单中未指定任何网络功能,则您的应用将没有网络功能,并且任何尝试连接到网络的尝试都会失败。

以下是最常用的联网功能。

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.

要在您的应用清单文件中定义一项或多项功能,请看下面的图像。

功能应用

通用Windows平台(UWP)通过针对以下对象包含大量网络API:

  • 查询设备的连接状态并连接到对等设备。
  • 与REST Web服务进行通信
  • 在后台下载大型媒体文件

网络技术

在通用Windows平台(UWP)中,开发人员可以使用以下联网技术,可以在许多不同的情况下使用它们。

插座

当您想通过自己的协议与其他设备通信时,可以使用套接字。

  • 您可以同时使用Windows.Networking.SocketsWinsock与通用Windows平台(UWP)应用程序开发人员与其他设备进行通信。

  • Windows.Networking.Sockets具有作为现代API的优势,旨在供UWP开发人员使用。

  • 如果您正在使用跨平台网络库或其他现有的Winsock代码,请使用Winsock API

以下代码显示了如何创建套接字侦听器。

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. 
}

以下代码显示SocketListener_ConnectionReceived事件处理程序的实现。

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

WebSockets协议通过Web在客户端和服务器之间提供了快速,安全的双向通信。通用Windows平台(UWP)开发人员可以使用MessageWebSocketStreamWebSocket类与支持WebSocket协议服务器连接。

重要功能是-

  • 在WebSocket协议下,数据立即通过全双工单套接字连接进行传输。

  • 它允许实时从两个端点发送和接收消息。

  • WebSockets非常适合用于实时游戏,在这种情况下,即时社交网络通知和信息(游戏统计信息)的最新显示需要安全并使用快速的数据传输。

以下代码显示了如何在安全连接上发送和接收消息。

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 
} 

以下代码显示了事件实现,它将从连接的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

HttpClientWindows.Web.Http命名空间API,使开发人员能够使用HTTP 2.0和HTTP 1.1协议发送和接收信息。

它可以用来-

  • 与Web服务或Web服务器通信。
  • 上载或下载许多小文件。
  • 通过网络流式传输内容。

以下代码显示如何使用Windows.Web.Http.HttpClientWindows.Web.Http.HttpResponseMessage发送GET请求。

//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; 
}