C # Learning Notes----Network (24th)----Sample Code

Source: Internet
Author: User
Tags getstream sendmsg mailmessage smtpclient

URI (Uniform Resource Identifier, Uniform Resource Identifier)

System.Net.WebClient Request File

The. NET Framework currently supports URIs that begin with http:, https:, and file: identifiers

WebClient download method, DownloadFile ()

New WebClient (); Client.downloadfile ("http://www.reuters.com","reuteshomepage.htm ");

WebClient retrieving data from a Web site method, OpenRead ()

New= Client.openread ("http://www.reuters.com");

WebClient OpenWrite ()

New= Webclient.openwrite ("http://localhost/accept/newfile.txt","  PUT"new  StreamWriter (stream); Streamwriter.writeline ("  HelloWorld"); StreamWriter.Close ();

WebClient UploadFile () and Uploaddata ()

New WebClient (); client. UploadFile ("http://www.ourwebsite.com/NewFile.htm","c:\\ websitefiles\\newfile.htm"); byte [] image; // code to initialize image so it contains all the binary datafor client. Uploaddata ("http://www.ourwebsite.com/NewFile.jpg", image);

WebRequest class, WebResponse class

The WebRequest class represents a request to send information to a particular URI, and the URI is passed as a parameter to the Create () method

The WebResponse class represents the data retrieved from the server. Calling the Webrequest.getresponse () method actually sends the request to the Web server and creates a response object to examine the returned data.

As with the WebClient object, you can get a data flow representing the data, which is obtained using the WebResponse.GetResponseStream () method.

WebRequest WRQ = WebRequest.Create ("http://www.reuters.com"==   New  StreamReader (STRM); string Line ;  while NULL ) {    listBox1.Items.Add (line);} Strm. Close ();

The Timeout property controls the WebRequest object waiting for the corresponding response time before throwing the WebException exception

Webexception.status property to see why an exception was generated

The KeepAlive property allows multiple requests to use the same connection through HttpWebRequest, saving the time to close and reopen the connection in subsequent requests

The AllowAutoRedirect property is dedicated to HttpWebRequest, which allows you to control whether Web requests should automatically follow the redirect response on the Web server

Credentials attribute Authentication

New NetworkCredential ("myusername","mypassword"= myCred;

Using a proxy, you need to use the WebProxy object

New WebProxy ("192.168.1.100",truenew networkcredential ("  user1","user1password"= WebRequest.Create ( " http://www.reuters.com "  == WRQ. GetResponse ();

In addition to the certificate, you need to design the user's domain

WebProxy WP =NewWebProxy ("192.168.1.100",true); WP. Credentials=NewNetworkCredential ("User1","User1password","MyDomain"); WebRequest WRQ= WebRequest.Create ("http://www.reuters.com"); Wrq. Proxy=WP; WebResponse WRs= Wrq. GetResponse ();

You can request pages asynchronously, using the BeginGetResponse () method and the EndGetResponse () method

WebRequest WRQ = WebRequest.Create ("http://www.reuters.com"); Wrq. BeginGetResponse (new AsyncCallback (Onresponse), WRQ);

WebBrowser controls

Non-webbrowse control, opening a Web page with a process in the System.Diagnostics namespace

New"iexplore.exe" "http://www.wrox.com"  ; Myprocess.start ();

Using the LinkLabel control

Private void linklabel1_linkclicked (object  Sender,linklabellinkclickedeventargs e) {      New  WebBrowser ();    Wb. Navigate ("http://www.wrox.com",true);}

Navigated events for WebBrowser controls

Private void webbrowser1_navigated (object  Sender,webbrowsernavigatedeventargs e) {    =  WebBrowser1.Url.ToString ();     this. Text = webBrowser1.DocumentTitle.ToString ();}

The GoBack () method of the WebBrowser control, the GoForward () method, the Stop (), the Refresh (), and the GoHome () method

Print () for the WebBrowser control

New WebBrowser (); WB. Navigate ("http://www.wrox.com"); WB. Print ();

Utility class

URIs and UriBuilder are two classes in the System namespace that represent URIs.

URI provides read-only property, UriBuilder property can read and write

IPAddress class represents IP address

IPAddress IPAddress = Ipaddress.parse ("234.56.78.9"); byte [] address = ipaddress.getaddressbytes (); string ipstring = ipaddress.tostring ();

Iphostentry class encapsulates information related to a particular host

The DNS class is able to communicate with the default DNS server, and the DNS class has two important static methods: the Resolve () method and the Gethostbyaddress () method

Iphostentry wroxhost = Dns.resolve ("www.wrox.com"= dns.gethostbyaddress ("  208.215.179.178");

System.Net.Sockets

The underlying class of the Socket is used to manage connections. Classes such as WebRequest, TcpClient, and UdpClient use this class internally

NetworkStream This class is derived from stream, which represents a stream of data from the network

SmtpClient allow messages to be sent via SMTP (mail)

TcpClient allow the creation and use of TCP connections

TcpListener allow listening for incoming TCP connection requests

UdpClient used to create a connection for a UDP client (UDP is an alternative protocol for TCP, but it is not widely used, mainly for local networks)

SmtpClient objects can send mail messages over SMTP

SmtpClient sc =NewSmtpClient ("mail.mySmtpHost.com"); SC. Host="mail.mySmtpHost.com"; MailMessage mm=Newmailmessage (); mm. Sender=NewMailAddress ("[email protected]","Bill Evjen"); mm. To.add (NewMailAddress ("[email protected]","Paul Reese") ); mm. To.add (NewMailAddress ("[email protected]","Wrox Marketing") ); mm. Cc. ADD (NewMailAddress ("[email protected]","Barry Pruett") ); mm. Subject="The latest Chapter"; mm. Body="<b>here You can put a long message</b>"; mm. Isbodyhtml=true; mm. Priority=Mailpriority.high; Attachment att=NewAttachment ("Myexcelresults.zip", MediaTypeNames.Application.Zip); mm. Attachments.Add (ATT); sc. Send (mm);

The Transmission Control Protocol (TCP) class provides an easy way to connect and send data between two endpoints

Endpoint is a combination of IP address and port number

The TcpListener class listens for incoming TCP connections with the start () method

When a connection request arrives, you can use the AcceptSocket () method to return a socket to communicate with the remote computer

or use the AcceptTcpClient () method to communicate through a high-level TcpClient object

Private voidBtnsend_click (ObjectSender,system.eventargs e) {TcpClient TcpClient=NewTcpClient (Txthost.text,int32.parse (Txtport.text)); NetworkStream NS=Tcpclient.getstream (); FileStream FS= File.Open ("Form1.cs", FileMode.Open); intdata =FS.    ReadByte (); while (Data!= -1) {ns. WriteByte ((byte) data); Data=FS.    ReadByte (); } fs.    Close (); Ns.    Close (); Tcpclient.close ();}

//Add a background thread PublicForm1 () {InitializeComponent (); Thread Thread=NewThread (NewThreadStart (Listen)); Thread. Start ();} Public voidListen () {IPAddress localaddr= Ipaddress.parse ("127.0.0.1"); Int32 Port=2112; TcpListener TcpListener=NewTcpListener (Localaddr,port); Tcplistener.start (); TcpClient TcpClient=tcplistener.accepttcpclient (); NetworkStream NS=Tcpclient.getstream (); StreamReader SR=NewStreamReader (NS); stringresult =Sr. ReadToEnd (); Invoke (NewUpdatedisplaydelegate (Updatedisplay),New Object[]{result}]; Tcpclient.close (); Tcplistener.stop ();}

The UdpClient class member function send () takes a byte array as an argument, and the Receive () function returns a byte array

UDP is a non-connected protocol that can specify the endpoint of a communication as a parameter to the Send () method and the Receive () method

UdpClient UdpClient =Newudpclient ();stringsendmsg ="Hello Echo Server";byte[] Sendbytes =Encoding.ASCII.GetBytes (sendmsg); Udpclient.send (Sendbytes,sendbytes.length,"someechoserver.net",7); IPEndPoint endPoint=NewIPEndPoint (0,0);byte[] rcvbytes = Udpclient.receive (refendPoint);stringRcvmessage = Encoding.ASCII.GetString (Rcvbytes,0, rcvbytes.length);//should print out "Hello Echo Server"Console.WriteLine (Rcvmessage);

The UdpClient class and the TcpClient class provide an abstraction layer on the lowest-level socket class

The socket class provides the highest level of control in network programming

Overriding the Tcpreceive application with the socket class

 Public voidListen () {Socket listener=NewSocket (ADDRESSFAMILY.INTERNETWORK,SOCKETTYPE.STREAM,PROTOCOLTYPE.TCP); Listener. Bind (NewIPEndPoint (Ipaddress.any,2112)); Listener. Listen (0); Socket Socket=Listener.    Accept (); Stream NetStream=NewNetworkStream (socket); StreamReader Reader=NewStreamReader (NetStream); stringresult =Reader.    ReadToEnd (); Invoke (Newupdatedisplaydelegate (Updatedisplay)New Object[] {result}); Socket.    Close (); Listener. Close ();}

The end is attached to the HTTP protocol detailed link HTTP protocol explained (really classic)

C # Learning Notes----Network (24th)----Sample Code

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.