首页 > 代码库 > C#学习笔记 ----网络(第24章)----示例代码

C#学习笔记 ----网络(第24章)----示例代码

URI (Uniform Resource Identifier,统一资源标识符)

 

System.Net.WebClient 请求文件

.NET Framework 目前支持以http:、https:和file:标识符开头的URI

 

WebClient下载方法,DownloadFile()

WebClient Client = new WebClient();Client.DownloadFile("http://www.reuters.com","ReutesHomepage.htm");

WebClient 从Web站点检索数据方法,OpenRead()

WebClient Client = new WebClient();Stream strm = Client.OpenRead("http://www.reuters.com");

WebClient OpenWrite()

WebClient webClient = new WebClient();Stream stream = webClient.OpenWrite("http://localhost/accept/newfile.txt","PUT");StreamWriter streamWriter = new StreamWriter(stream);streamWriter.WriteLine("Hello World");streamWriter.Close();

WebClient UploadFile()和UploadData()

WebClient client = 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 data forclient.UploadData("http://www.ourwebsite.com/NewFile.jpg",image);

 

WebRequest类、WebResponse类

WebRequest类代表要给某个特定URI发送信息的请求,URI作为参数传递给Create()方法

WebResponse类代表从服务器检索的数据。调用WebRequest.GetResponse()方法,实际上是把请求发给Web服务器,并创建一个Response对象,以检查返回的数据。

与WebClient对象一样,可以得到一个代表数据的数据流,使用WebResponse.GetResponseStream()方法获得。

WebRequest wrq = WebRequest.Create("http://www.reuters.com");WebResponse wrs = wrq.GetResponse();Stream strm = wrs.GetResponseStream();StreamReader sr = new StreamReader(strm);string line;while((line = sr.ReadLine()) != null){    listBox1.Items.Add(line);}strm.Close();

Timeout属性  控制WebRequest对象在抛出WebException异常之前等待相应的响应时间

WebException.Status属性  查看产生异常的原因

KeepAlive属性  通过HttpWebRequest,允许多个请求使用同一个连接,在后续的请求中节省关闭和重新打开连接的时间

AllowAutoRedirect属性  专用于HttpWebRequest,使用这个属性可以控制Web请求是否应自动跟随Web服务器上的重定向响应

Credentials属性  身份验证

NetworkCredential myCred = new NetworkCredential("myusername","mypassword");wrq.Credentials = myCred;

使用代理,需要使用WebProxy对象

WebProxy wp = new WebProxy("192.168.1.100",true);wp.Credentials = new NetworkCredential("user1","user1Password");WebRequest wrq = WebRequest.Create("http://www.reuters.com");wrq.Proxy = wp;WebResponse wrs = wrq.GetResponse();

除了证书,还需要设计用户的域

WebProxy wp = new WebProxy("192.168.1.100",true);wp.Credentials = new NetworkCredential("user1","user1Password","myDomain");WebRequest wrq = WebRequest.Create("http://www.reuters.com");wrq.Proxy = wp;WebResponse wrs = wrq.GetResponse();

可以异步请求页面,使用BeginGetResponse()方法和EndGetResponse()方法

WebRequest wrq = WebRequest.Create("http://www.reuters.com");wrq.BeginGetResponse(new AsyncCallback(OnResponse),wrq);

 

WebBrowser控件

非WebBrowse控件,使用System.Diagnostics名称空间中的Process打开Web页

Process myProcess = new Process();myProcess.StartInfo.FileName = "iexplore.exe";myProcess.StartInfo.Arguments = "http://www.wrox.com";myProcess.Start();

 

使用LinkLabel控件

private void linkLabel1_LinkClicked(object sender,LinkLabelLinkClickedEventArgs e){    WebBrowser wb = new WebBrowser();    wb.Navigate("http://www.wrox.com",true);}

WebBrowser控件的Navigated事件

private void webBrowser1_Navigated(object sender,WebBrowserNavigatedEventArgs e){    textBox1.Text = webBrowser1.Url.ToString();    this.Text = webBrowser1.DocumentTitle.ToString();}

WebBrowser控件的GoBack()方法、GoForward()方法、Stop()、Refresh()和GoHome()方法

WebBrowser控件的Print()

WebBrowser wb = new WebBrowser();wb.Navigate("http://www.wrox.com");wb.Print();

 

实用工具类

Uri和UriBuilder是System名称空间中的两个类,用于表示URI。

Uri提供只读属性,UriBuilder属性可读写

 

IPAddress类代表IP地址

IPAddress ipAddress = IPAddress.Parse("234.56.78.9");byte[] address = ipAddress.GetAddressBytes();string ipString = ipAddress.ToString();

IPHostEntry类  封装与某台特定的主机相关的信息

Dns类  能够与默认的DNS服务器进行通信,Dns类有两个重要的静态方法:Resolve()方法和GetHostByAddress()方法

IPHostEntry wroxHost = Dns.Resolve("www.wrox.com");IPHostEntry wroxHostCopy = Dns.GetHostByAddress("208.215.179.178");

 

System.Net.Sockets

Socket  这个底层的类用于管理连接。WebRequest、TcpClient和UdpClient等类在内部使用这个类

NetworkStream  这个类是从Stream派生的,它表示来自网络的数据流

SmtpClient  允许通过SMTP发送消息(邮件)

TcpClient  允许创建和使用TCP连接

TcpListener  允许侦听引入的TCP连接请求

UdpClient  用于为UDP客户创建连接(UDP是TCP的一种替代协议,但它没有得到广泛的使用,主要用于本地网络)

 

SmtpClient对象可以通过SMTP传送邮件消息

SmtpClient sc = new SmtpClient("mail.mySmtpHost.com");sc.Host = "mail.mySmtpHost.com";MailMessage mm = new MailMessage();mm.Sender = new MailAddress("evjen@yahoo.com","Bill Evjen");mm.To.Add(new MailAddress("editor@wrox.com","Paul Reese"));mm.To.Add(new MailAddress("marketing@wrox.com","Wrox Marketing"));mm.CC.Add(new MailAddress("publisher@wrox.com","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 = new Attachment("myExcelResults.zip",MediaTypeNames.Application.Zip);mm.Attachments.Add(att);sc.Send(mm);

 

传输控制协议(TCP)类为连接和发送两个端点之间的数据提供了简单的方法

端点是IP地址和端口号的组合

TcpListener类用Start()方法侦听引入的TCP连接

当连接请求到达时,可以使用AcceptSocket()方法返回一个套接字,以与远程计算机通信

或使用AcceptTcpClient()方法通过高层TcpClient对象进行通信

private void btnSend_Click(object sender,System.EventArgs e){    TcpClient tcpClient = new TcpClient(txtHost.Text,Int32.Parse(txtPort.Text));    NetworkStream ns = tcpClient.GetStream();    FileStream fs = File.Open("form1.cs",FileMode.Open);    int data =http://www.mamicode.com/ fs.ReadByte();    While(data != -1)    {            ns.WriteByte((byte)data);        data = fs.ReadByte();    }    fs.Close();    ns.Close();    tcpClient.Close();}

//添加后台线程public Form1(){ InitializeComponent(); Thread thread = new Thread(new ThreadStart(Listen)); thread.Start();}public void Listen(){ IPAddress localAddr = IPAddress.Parse("127.0.0.1"); Int32 port = 2112; TcpListener tcpListener = new TcpListener(localAddr,port); tcpListener.Start(); TcpClient tcpClient = tcpListener.AcceptTcpClient(); NetworkStream ns = tcpClient.GetStream(); StreamReader sr = new StreamReader(ns); string result = sr.ReadToEnd(); Invoke(new UpdateDisplayDelegate(UpdateDisplay),new object[]{result}); tcpClient.Close(); tcpListener.Stop();}

 

UdpClient类  成员函数Send()把一个字节数组作为参数,Receive()函数则返回一个字节数组

UDP是一个无连接的协议,可以指定把通信的端点作为Send()方法和Receive()方法的一个参数

UdpClient udpClient = new UdpClient();string sendMsg = "Hello Echo Server";byte[] sendBytes = Encoding.ASCII.GetBytes(sendMsg);udpClient.Send(sendBytes,sendBytes.Length,"SomeEchoServer.net",7);IPEndPoint endPoint = new IPEndPoint(0,0);byte[] rcvBytes = udpClient.Receive(ref endPoint);string rcvMessage = Encoding.ASCII.GetString(rcvBytes,0,rcvBytes.Length);//should print out "Hello Echo Server"Console.WriteLine(rcvMessage);

 

UdpClient类和TcpClient类在最底层的Socket类上提供了一个抽象层

Socket类提供了网络编程中最高级的控制

用Socket类重写TcpReceive应用程序

public void Listen(){    Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);    listener.Bind(new IPEndPoint(IPAddress.Any,2112));    listener.Listen(0);        Socket socket = listener.Accept();    Stream netStream = new NetworkStream(socket);    StreamReader reader = new StreamReader(netStream);    string result = reader.ReadToEnd();    Invoke(new UpdateDisplayDelegate(UpdateDisplay)        new object[] {result});    socket.Close();    listener.Close();}

 

结尾附上HTTP协议详解链接HTTP协议详解(真的很经典)

C#学习笔记 ----网络(第24章)----示例代码