Windows 10 Development Network Programming tutorial

Source: Internet
Author: User
Tags html page http request sendmsg serialization socket port number

The main content of this tutorial: HttpClient class, Socket communication, WCF communication





HttpClient class





There are two httpclient classes in UWP that can be used for network communication. System.Net.Http.HttpClient and Windows.Web.Http.HttpClient, the difference in use is not very large, but we give priority to the latter because it is located in Windows.Foundation.UniversalApiContract assemblies, which are local code, are more efficient. Our main study is also Windows.Web.Http.HttpClient.





Using the HttpClient class, we can send an HTTP request to the specified URI and get the data returned from the server. Requests are initiated in the form of Get, POST, put, and DELETE, which are asynchronous requests. We also need a Httpresponsemessage object to declare the HTTP response message received from the HTTP request.





HttpClient httpclient = new HttpClient ();





Add User Agent Headers





HTTPCLIENT.DEFAULTREQUESTHEADERS.ADD ("User-agent", "mozilla/5.0" (compatible; MSIE 10.0; Windows NT 6.2; WOW64; trident/6.0) ");








Httpresponsemessage response = await Httpclient.getasync (new Uri (Tburl.text));//Send request, here is the way to get, other ways like





Response. Ensuresuccessstatuscode ()//Ensure successful request











Buffer method Read return result





Ibuffer buffer = await response. Content.readasbufferasync ();





Stream mode Read return result





Iinputstream inputstream= await response. Content.readasinputstreamasync ();





Read the return result in string mode





String result = await response. Content.readasstringasync ();








This is the general way to implement HTTP requests on the HttpClient class, OK, see the regular demo:





Request HTML page:We request the returned HTML, which is finally converted to a string type, and then gives this string value to the WebView control's Navigatetostring method, which automatically handles the HTML markup. PS: If you think this is better than directly to the WebView control of the Navigate method, anyway, you will display the string value with other text controls! Also, read the string directly with the Readasstringasync method on the line, the back of the only to toss about.








  private async void btn_get_click (Object sender, routedeventargs e)     {        //http://static.cnblogs.com/images/ Logo_small.gif         //http://www.cnblogs.com/czhwust/p/win10_ File.html         HttpClient httpClient = new 
HttpClient ();         httpclient.defaultrequestheaders.add ("User-agent", ) mozilla/5.0  (compatible; msie 10.0; windows nt 6.2; WOW64;
trident/6.0) ");         if  (String.IsNullOrEmpty (tburl.text))          {             Tbstatus.
text =  "The URL entered is null";        &NBSP}         else  &Nbsp;      {             try             {                                   tbstatus.
text =  "  Wait for response ...";                 
Httpresponsemessage response =  await httpclient.getasync (New Uri (TbUrl.Text));                              response. Ensuresuccessstatuscode ()//ensure successful request                  tbstatus. Text = response. statuscode +  "  "  + response.
Reasonphrase;                 //Request HTML                  //string method read return result                  string result  = await response.
Content.readasstringasync ();                 wv.
Navigatetostring (result);
                //buffer Way to read                 //ibuffer  buffer = await   response.
Content.readasbufferasync ();                 //using  ( Var datareader = dAtareader.frombuffer (buffer)                  //{                 //    string result = datareader.readstring (buffer.
Length);                 //     wv.
Navigatetostring (result);                 //}                  //stream Way to read                  //var  Inputstream = await  response.
Content.readasinputstreamasync ();                 // stream  stream=  InputStream.
Asstreamforread ();                 // using   (Streamreader reader=new streamreader (stream))                  // {                 //   string result= reader.
ReadToEnd ();                 //    wv.
Navigatetostring (result);                 // }                              }              catch  (Exception ex)              {                 tbstatus. Text = ex.
ToString ();             }          }     }




  Request Picture: in the request picture, the Writetostreamasync method is most simple, the back of the same is to toss, but you can carefully understand ... PS: Directly to the network image of the address assignment to the image control of the Source property can display pictures, I was smashed the site! )


Private async void btn_get_click (object sender, routedeventargs e)   
  {        //http://static.cnblogs.com/images/logo_small.gif         //http://www.cnblogs.com/czhwust/p/win10_file.html   
      httpclient httpclient = new httpclient ();         httpclient.defaultrequestheaders.add ("User-agent", ) mozilla/5.0  (compatible; msie 10.0; windows nt 6.2; WOW64;
trident/6.0) ");         if  (String.IsNullOrEmpty (tburl.text))          {             Tbstatus.
text =  "The URL entered is null";        &NBSP}         else          {            try              {                 tbstatus.
text =  "  Wait for response ...";                 
Httpresponsemessage response = await httpclient.getasync (New Uri (TbUrl.Text));                 response. Ensuresuccessstatuscode ()//ensure successful request                  tbstatus. Text = response. statuscode +  " "  + response.
Reasonphrase;                 //Request Pictures                           
        bitmapimage bitmap = new bitmapimage ();                 //    writetostreamasync                  using  (Inmemoryrandomaccessstream stream = new inmemoryrandomaccessstream ())                 {                      await response.
Content.writetostreamasync (stream);                      stream.
Seek (0ul);       &nbsP;             bitmap.
SetSource (stream);                      img.
source = bitmap;                 }                  //          iinputstream   >>  irandomaccessstream                  //IInputStream  Inputstream = await response.
Content.readasinputstreamasync ();                 //using  ( Irandomaccessstream randomaccessstream = new inmemoryrandomaccessstream ())                  //{                 //    using  ( Ioutputstream outputstream = randomaccessstream.getoutputstreamat (0))                  //    {                 //   
     await randomaccessstream.copyasync (Inputstream, outputstream);                 //  
      randomaccessstream.seek (0);                 //         bitmap.
SetSource (Randomaccessstream);                 //         img.
source = bitmap;                 //     }                 / /}                 // 
         ibuffer  >> irandomaccessstream                 //ibuffer  buffer = await response.
Content.readasbufferasync ();                 //using  ( Irandomaccessstream randomaccessstream = new inmemoryrandomaccessstream ())  &Nbsp;              //{                 //    using
  (Datawriter datawriter = new datawriter (Randomaccessstream.getoutputstreamat (0))                 //     {                / /        datawriter. WriteBuffer (Buffer, 0, buffer.
Length);                 //         await datawriter.
Storeasync ();                 //         randomaccessstrEam.
Seek (0);                 //         bitmap.
SetSource (Randomaccessstream);                 //         img.
source = bitmap;                 //     }                 / /}             }              catch  (Exception ex)              {                 tbstatus. Text = ex.
ToString ();             }         }     }




 socket Communications

  Socket communication is a point-to-point communication technology that we can use to develop point-to-point interactive communication software. As a common underlying network communication technology, socket has the characteristics of simple and easy to use, stable connection and strong data transmission ability. HTTP communication is a temporary, stateless communication, the HTTP connection is disconnected when the client makes an HTTP request, and the server responds once, and when we want to get new data, we can only send another HTTP request. Socket communication is a communication handle that is connected with IP address and port number, and is a network communication protocol with End-to-end communication model. Socket to ensure the durability of the connection, once the successful connection with the server, the server's corresponding port will be in the open state, at this time the client can be established through the socket channel, to the server open the port to issue operational instructions, and the client can also get the service side of the real-time feedback information, The socket does not end the entire connection process until the program issues a disconnect instruction or the network is disconnected.

  Socket communication supports two modes of operation. One is based on TCP mode, the mode is connection-oriented, sequential reliable delivery, the other is UDP mode, it is connectionless, less resource consumption of unreliable delivery. For more detailed differences between the two, please own Baidu to understand. Socket communication-related classes in UWP are located under the Windows.Networking.Sockets namespace, and the Streamsocket class corresponds to the Udp,datagramsocket class corresponding to TCP.

  Direct start Demo:

  First, we want to complete the service-side coding and create a new console application. (Put out all the code, not too much explanation.) )    


 static void main (String[] args)     {     
   int receiveLength;         ipendpoint ipendpoint = new ipendpoint (
ipaddress.any, 9900);         socket newsocket = new socket (
ADDRESSFAMILY.INTERNETWORK, SOCKETTYPE.STREAM,PROTOCOLTYPE.UDP);
        newsocket.bind (IPEndPoint);
        newsocket.listen (10);
        console.writeline ("  Waiting for Client connection  ");
        socket client = newsocket.accept ();         IPEndPoint clientIp =  (ipendpoint) client.
Remoteendpoint;         console.writeline ("  Connection client address  :"  + clientip.address +  ", Port slogan:"  + clientip.port);         while  (True)          {            byte[] data = 
new byte[1024];             receivelength = client.
Receive (data);             console.writeline ("  Get length of string
  " + receivelength);
            if  (receivelength == 0)
                break;             string getData = 
Encoding.UTF8.GetString (data, 0, receivelength);         &Nbsp;   console.writeline ("  data obtained from the client  :"  + getdata);             byte [] send = new
 byte[1024];             send = 
Encoding.UTF8.GetBytes ("RESPONSE :"  + getdata);             client. Send (send, send.
Length, socketflags.none);         }         
Console.WriteLine ("discnnected from "  + clientip.address);         client.
Close ();
        newsocket.close ();     }



   then the client, where it is necessary to note that when the client sends a message to the server, it also reads the message sent to the client by the server (the message that the server sends to the client is the message sent by the response:+ client). &NBSP


Private async void btnconnect_click (object sender, routedeventargs e)      {        try          {            socket = new
 streamsocket ();             await socket. ConnectAsync (New hostname (Tbip.text),  tbport.text)//connection to the server       
      tbInfo.Text =  "  Connection Success";        &NBSP}         catch  ( EXCEPTION EX)         {             tbInfo.Text =  "  Connection Server error:" +ex.
ToString ();         }    &nbsp} &Nbsp;   private void btnclose_click (Object sender, routedeventargs e)     {        //Disconnect Build          reader.
Dispose ();         writer.
Dispose ();         socket.
Dispose ();
        tbInfo.Text =  "  Close success";    &NBSP}     private void btnsend_click (Object sender,  routedeventargs e)     {        string
 str = tbMsg.Text;         sendmsg (Str,socket);//Send message       
   private async void sendmsg (String str, streamsocket socket)     {     &nbsP;  try         {             //Send data stream              Writer = new datawriter (socket.
OutputStream);             writer.
WriteString (str);             await writer.
Storeasync ();             //Read Data stream              reader = new datareader (socket.
InputStream);             reader.
inputstreamoptions = inputstreamoptions.partial;             await reader.
LoadAsync (1024);           &Nbsp; string data = reader. ReadString (reader.
Unconsumedbufferlength);             tbreceivedmsg.text += data
 +  "\ r \ n";        &NBSP}         catch  ( EXCEPTION EX)         {             tbInfo.Text =  "  exception occurred:" +ex.
ToString ();         }     }



Run Result:



WCF Communications

WCF (Windows communication Foundation) is also an important data communication technology, introduced in the. NET Framework 3.0, with the main advantages of service integration, which makes distributed development more flexible and stable. When a client communicates with a WCF service, it requires a proxy, which is to add a service reference.

Let's start by coding the WCF Services Section and create a new asp.net-empty Web application in the Visual C # language. We need to add a DataClass.cs class file and a newsdataservice.svc WCF service file.

DataClass.cs:

When we add [DataContract], we may not be able to import the namespace, when we want to manually add the reference System.Runtime.Serialization, which is the detailed path C:\Program Files (x86) \reference Assemblies\microsoft\framework\. Netframework\v4.5\system.runtime.serialization.dll


namespace wcfserver {[DataContract] Public  class dataclass {    [ DataMember]     public string newstime { set; get;&nbsp      [datamember]     public string NewsTitle { get;  set; }      }} Newsdataservice.svc:public class newsdataservice  : inewsdataservice {   public dataclass [] news ()      {        list<dataclass> newsdata = new  List<DataClass> ()         {             new dataclass {newstitle= "This is news headline 1", NewsTime= "2015-10-10"  },             new dataclass { Newstitle= "This is news headline 2",Newstime= "2015-10-11"               new  Dataclass {newstitle= "This is news headline 3", Newstime= "2015-10-12"  },              new dataclass {newstitle= "This is news headline 4", Newstime= "2015-10-13"  },              new dataclass {newstitle= "This is news headline 5"
, newstime= "2015-10-14"  },         };
        return newsdata.toarray ();    &NBSP}}




INewsDataService.cs:


Namespace Wcfserver
{
[ServiceContract] public
interface Inewsdataservice
{
[ OperationContract]
dataclass[] News ();
}



Then the client part is encoded. First we want to add the service reference (see this option in the References node in Solution Explorer), then in the following dialog box "address" Enter the URI of the WCF server, click "Go", etc. loaded, customize a namespace name, click "OK" can be, You can then invoke the WCF service on the server at the client.



We first have to run the server, the client can invoke, when running the server, we may run the project directly, will be an error (forbidden), at this time, we can select the Newsdataservice.svc, and then right-click, select "View in Browser", The effect of the top right figure appears, ok!


Client Program Interface section:


<grid background= "{Themeresource applicationpagebackgroundthemebrush}" >      <textblock x:name= "TextBlock"  horizontalalignment= "left"  margin= "49,54,0,0"   textwrapping= "Wrap"  text= "WCF Network Communications"  verticalalignment= "Top"/>     <listview  x:name= "ListView"  horizontalalignment= "left"  height= "266"  margin= "49,118,0,0"   Verticalalignment= "Top"  width= "228" >         < Listview.itemtemplate>             < Datatemplate>                  <stackpanel orientation= "Horizontal" >                      <textblock text= "{Binding  Newstitle} "></TextBlock>    &NBsp;                < Textblock text= "{binding newstime}" ></TextBlock>                  </StackPanel>              </DataTemplate>         </ Listview.itemtemplate>     </ListView>     <button x: Name= "Btn_getdata"  content= "Fetch data"  horizontalalignment= "left"  margin= "49,409,0,0"   Verticalalignment= "Top"  click= "Btn_getdata_click"/> </Grid>


Background code:

Private async void Btn_getdata_click (object sender, RoutedEventArgs e)
{
newsdataserviceclient client        = new Newsdataserviceclient ();
observablecollection<dataclass> data = await client.        Newsasync ();
Listview.itemssource = data;
}


Operation Effect:


Then we'll see how to invoke the Web Service. This is essentially the same as invoking a WCF service, first of all adding a service reference (Http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx), in the http:// webservice.webxml.com.cn This site can find a lot of Web service to call (but it seems often not open), and then these lines of code OK

Private async void Btn_getdata_click (object sender, RoutedEventArgs e)
{
mobilecodewssoapclient client        = new Mobilecodewssoapclient ();
String result=await client.getmobilecodeinfoasync (Tbtel.text, "");
Txtresult.    Text = result;
}


Run Result:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.