The network of C #

Source: Internet
Author: User
Tags getstream sendmsg mailmessage server port smtpclient

First of all, I'm sorry, some time ago to turn off the function of the comment, but now this function to open, welcome small partners to shoot bricks.

1 Network

In a networked environment, the two namespaces we are most interested in are System.Net and System.Net.Sockets. System.Net namespaces are typically related to high-priced operations, such as uploading and downloading Web requests using HTTP and other protocols, while the System.Net.Sockets namespace contains classes that are typically related to lower-level operations. If you want to use sockets or tcp/p directly Protocol that is useful for classes in this namespace.

2WebClient class

If you only want to request a file from a specific URL, you can use the simplest. Net class is System.Net.WebClient

2.1 Downloading files

DEMO:

1  WebClient client = new WebClient (); 2             Stream stream = client. OpenRead ("http://www.baidu.com"); 3             StreamReader reader = new StreamReader (stream), 4             string line = null, 5 while             (line = reader. ReadLine ()) = null) 6             {7                 Console.WriteLine (line); 8             } 9             reader. Close (): Ten             stream. Close ();             console.readline ();
2.2 File Upload

The WebClient class also provides the UploadFile () and Uploaddata () methods. Although this class is convenient to use, it has very limited functionality and, in particular, it cannot be used to provide authentication.

3WebRequest class and WebResponse class

The Webrequet class represents a request to send information to a particular URL, and the URL is passed as a parameter to the Create () method. The WebResponse class represents retrieving data from the server, calling the Webrequest.getresponse () method, actually sending the request to the Web server, and creating a response object to check the return data.

1  WebRequest WRQ = WebRequest.Create ("http://www.ithome.com/"); 2             WebResponse WRs = Wrq. GetResponse (); 3             Stream stream = WRs. GetResponseStream (); 4             StreamReader reader = new StreamReader (stream), 5             string line, 6 while             (line = reader. ReadLine ()) = null) 7             {8                 Console.WriteLine (line); 9             }10             stream. Close ();             console.readline ();
3.1 Authentication

Another property in the WebRequest class is the credentials property. If an authentication certificate is required to accompany the request, you can create an instance of the NetworkCredential class with a user name and password before calling the GetResponse () method.

1   networkcredential NC = new NetworkCredential ("username", "password"); 2             WRQ. Credentials = NC;
3.2 Using proxies

Many companies need to use a proxy server for all types of HTTP or FTP requests. Proxy servers often use some form of security (usually a user name and password) to route all requests and responses from the company. For applications that use WebClient objects or WebRequest objects, these proxy servers need to be considered, as in the above, the WebProxy object needs to be used before the call

1 WebProxy WP = new WebProxy ("192.168.1.100", true); 2             WP. credentials= new NetworkCredential ("username", "password");     3             WebRequest WRQ = WebRequest.Create ("http://www.ithome.com/"); 4             WRQ. Proxy = wp;5             WebResponse WRs = Wrq. GetResponse ();
If you need to design a user's domain in addition to the certificate, you should use a different signature on the NetworkCredential instance
1  WebProxy WP = new WebProxy ("192.168.1.100", true); 2             WP. credentials= new NetworkCredential ("username", "password", "domain");     3             WebRequest WRQ = WebRequest.Create ("http://www.ithome.com/"); 4             WRQ. Proxy = wp;5             WebResponse WRs = Wrq. GetResponse ();
4 Display the results of the output as HTML pages
1  Process myproess = new process (); 2             myproess. Startinfo.filename = "Iexplore.exe"; 3             myproess. startinfo.arguments = "http://www.ithome.com/"; 4             myproess. Start ();

The above code will open IE as a separate window, and the application is not connected to the new window, so the browser cannot be controlled.

4.1 Simple Web browsing from the application

You can use the WebBrowser control if you want to open the Web page in your application.

5 Utility Class 5.1URL

URLs and Urlbulider are the two classes in the system (note: not System.Net) namespace that are used to represent URIs. The UriBuilder class allows you to construct a URL by taking a given string as part of a URL.

Uri url = new Uri ("http://www.ithome.com");
5.2 IP address and DNS name

. NET class Ipadress classes and iphostentry for IP addresses

6 lower-level protocols
    • The underlying class for sockets is used to manage connections, WebRequest, TcpClient and other classes that use this class internally.
    • NetworkStream This class derives 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 is used to create for UDP clients (UDP is an alternative protocol for TCP, but it is primarily used for local networks)
6.1 Using SmtpClient

The SmtpClient object can send mail messages through SMTP,

  MailMessage mymail = new MailMessage ();                Send end to receive end email address              mymail = new MailMessage ("Sender @163.com", "Recipient @qq.com");            Mymail.subject = "1";            Establish the Sending object client, verify the mail server, server port, user name, and password              smtpclient client = new SmtpClient ("123.125.50.133");            Client. Credentials = new NetworkCredential ("username", "password");            Client. Send (MyMail);

However, there is a problem, this method will send more than 10 messages when the error, the following is attached to a number of ways to send

SendEmail
6.2 Using the TCP class

The Transmission Control Protocol (TCP) class provides an easy way to connect and send data between two endpoints. The endpoint is a combination of IP address and port number. The TcpClient class encapsulates a TCP connection, provides many properties to control the connection, including buffering, buffer size, and timeout, and requests NetworkStream objects through the GetStream () method to be accompanied by read-write functionality.
The TcpListener class listens for incoming TCP connections with the Start () method, and when a connection request arrives, you can use the AcceptSocket () method to return a socket to communicate with a remote computer, or to use the accepttcpclient () The TcpClient method communicates through high-level objects.
6.3TCP and UDP

UDP is a simple protocol with little or no functionality and has little overhead. Developers often use UDP in applications where speed and performance requirements are higher than reliability, for example, video streaming. Instead, TCP provides many features to ensure the transmission of data, it also provides error correction, and the ability to retransmit them when data loss or packet corruption occurs. Finally, TCP caches incoming and outgoing data, and ensures that a cluttered array of packets is reorganized during the transfer process before the packet is delivered to the application. Even with some extra overhead, TCP is still the most widely used protocol on the Internet, because it has very high reliability.

6.4UDP class
1   udpclient udpclient = new UdpClient (); 2             string sendmsg = "Hello"; 3             byte[] sendbytes = Encoding.ASCII.GetBytes (sendmsg); 4             UdpClient. Send (Sendbytes,sendbytes.length, "Somechoserver.net", 7), 5             ipendpoint endPoint = new IPEndPoint (0,0); 6             byte[ ] Rcvbytes = UdpClient. Receive (ref endPoint); 7             String rcvmessage = Encoding.ASCII.GetString (rcvbytes,0,rcvbytes.length);
6.5TcpSend and tcpreceive examples
Tcpsend-Side code:
1  TcpClient TcpClient = new TcpClient (host, port number), 2              networkstream ns = Tcpclient.getstream (), 3              FileStream fs = F Ile. Open ("Form1.cs", FileMode.Open); 4  5            int data = fs. ReadByte (); 6  7 while             (data! =-1) 8            {9                ns. WriteByte (byte), Data                  = fs. ReadByte ();             }12              fs. Close (),             ns. Close ();              tcpclient.close ();

Tcpreceive End:
 1 Thread theard = new Thread (new ThreadStart (Listen)); Winfrom program, only a textbox for Txtdisplay 2 Theard. Start ();//To avoid animation of the interface, put it in the thread 3 4 5 public void Listen () 6 {7 IPAddress localaddr = Ipaddress.parse ("127.0.0.1");//native 8 int port = 2112;//port number to be consistent with Tcpsend end 9 TcpListener tcplistenter = new Tcplistene R (localaddr, port); Tcplistenter.start (); TcpClient TcpClient = Tcplistenter.accepttcpcl              Ient (); NetworkStream ns = Tcpclient.getstream (); StreamReader sr = new StreamReader (NS); 15 string result = Sr. ReadToEnd (); + Invoke (new Updatedisplaydelegate (Updatedisplay), new object[] {result}); TcpC Lient. Close (); Tcplistenter.stop ();}20 public void Updatedisplay (string text) 22 {2 3 Txtdisplay.text = text;24}25}26 public delegate void Updatedisplaydelegate (String tEXT); 

6.5 Socket Class

The socket class provides the highest level of control in network programming.
To build the server console application:
View Code
Client code:
View Code
6.6Websocket
The WebSocket protocol is used for full duplex communication, typically between the browser and the server.
Client
Service Side

The network of C #

Related Article

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.