码迷,mamicode.com
首页 > Windows程序 > 详细

06.C#网络编程

时间:2015-03-05 16:27:23      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:

1.WebClient类

(1)WebClient类的主要方法
    DownloadXXX()方法:    下载URI资源文件
    OpenXXX()方法:        打开URI资源流
    UploadXXX()方法:      上传资源到URI
(2)DownloadData()方法
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. WebClient web = new WebClient();
  6. byte[] temp = web.DownloadData("http://www.baidu.com");//下载URI资源文件
  7. string Response = Encoding.UTF8.GetString(temp);//解码
  8. Console.WriteLine(Response);
  9. Console.Read();
  10. }
  11. }
(3)OpenRead()方法
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. WebClient web = new WebClient();
  6. Stream st = web.OpenRead("http://www.baidu.com");//打开URI资源流
  7. StreamReader sr = new StreamReader(st);
  8. string Response = sr.ReadToEnd();
  9. Console.WriteLine(Response);
  10. Console.Read();
  11. }
  12. }
(4)UploadData()方法
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. WebClient web = new WebClient();
  6. string str = "李志伟";
  7. byte[] response = web.UploadData("http://www.baidu.com", Encoding.Default.GetBytes(str));
  8. Console.WriteLine(Encoding.Default.GetString(response));//解码
  9. Console.Read();
  10. }
  11. }
    上传数据时出现问题,百度报错!这是因为没有权限。
(5)总结WebClient类
    虽然WebClient类使用简单,但是其功能有限,特别是不能使用它提供身份验证证书。这样,在上传数据时问题就出现了,许多站点不接受没有身份验证的上传文件。这是由于WebClient类是非常一般的类,可以使用任意协议发送请求和接受响应(如:HTTP、FTP等)。但它不能处理特定于任何协议的任何特性,例如,专用于HTTP的cookie。如果想利用这些特性就需要使用WebRequest类与WebResponse类为基类的一系列类。

2.WebRequest类与WebResponse类

(1)WebRequest类与WebResponse类简介
    WebRequest类与WebResponse类是抽象类,其子类对象代表某个特定URI协议的请求对象或响应对象。调用WebRequest.Create()方法得到WebResponse对象。调用WebResponse对象的GetResponse()方法得到WebResponse对象。
(2)使用示例
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. WebRequest req = WebRequest.Create("http://www.baidu.com");//得到请求对象
  6. WebResponse res = req.GetResponse();//得到相应对象
  7. Stream strm = res.GetResponseStream();//得到相应数据流
  8. StreamReader sr = new StreamReader(strm);
  9. Console.WriteLine(sr.ReadToEnd());
  10. Console.Read();
  11. }
  12. }
(3)WebRequest类与WebResponse类的子类(继承结构)
 技术分享
(4)HttpWebRequest类与HttpWebResponse类使用示例
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. string uri = "http://www.baidu.com";
  6. HttpWebRequest httpRe = (HttpWebRequest)HttpWebRequest.Create(uri);
  7. HttpWebResponse httpRes = (HttpWebResponse)httpRe.GetResponse();
  8. Stream strm = httpRes.GetResponseStream();//得到相应数据流
  9. StreamReader sr = new StreamReader(strm);
  10. Console.WriteLine(sr.ReadToEnd());
  11. Console.Read();
  12. }
  13. }
    这里以HTTP协议为例使用了对应了类,其他协议的类的使用方法与此类似。
(5)身份验证
    如果需要把身份验证证书附带在请求中,就使用WebRequest类中的Credentials属性。
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. WebRequest req = WebRequest.Create("http://www.baidu.com");//得到请求对象
  6. NetworkCredential cred = new NetworkCredential("userName", "password");
  7. req.Credentials = cred;//调用GetResponse()之前赋值
  8. WebResponse res = req.GetResponse();//得到相应对象
  9. Stream strm = res.GetResponseStream();//得到相应数据流
  10. StreamReader sr = new StreamReader(strm);
  11. Console.WriteLine(sr.ReadToEnd());
  12. Console.Read();
  13. }
  14. }
(6)使用代理
    使用代理服务器需要用到WebRequest类中的Proxy属性,以及WebProxy对象。
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. WebRequest req = WebRequest.Create("http://www.baidu.com");//得到请求对象
  6. NetworkCredential cred = new NetworkCredential("userName", "password","Domain");
  7. WebProxy wp = new WebProxy("192.168.1.100", true);//设置代理服务器地址
  8. req.Credentials = cred;//调用GetResponse()之前赋值
  9. req.Proxy = wp;//调用GetResponse()之前赋值
  10. WebResponse res = req.GetResponse();//得到相应对象
  11. Stream strm = res.GetResponseStream();//得到相应数据流
  12. StreamReader sr = new StreamReader(strm);
  13. Console.WriteLine(sr.ReadToEnd());
  14. Console.Read();
  15. }
  16. }
(7)异步请求
    若需要使用异步请求,就可以使用BeginGetRequestStream()、EndGetRequestStream()与BeginGetResponse()、EndGetResponse()方法。使用异步请求就不需要等待请求的响应,主线程不必阻塞可以直接向下执行。示例如下:
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. WebRequest req = WebRequest.Create("http://www.baidu.com");//得到请求对象
  6. req.BeginGetResponse(new AsyncCallback(Callback), req);//得到相应对象
  7. Console.WriteLine("异步请求已发送...");
  8. Console.Read();
  9. }
  10. //回调函数
  11. private static void Callback(IAsyncResult ar)
  12. {
  13. Thread.Sleep(5000);//休眠5秒
  14. WebRequest req = (WebRequest)ar.AsyncState;
  15. WebResponse res = req.EndGetResponse(ar);
  16. Stream strm = res.GetResponseStream();//得到相应数据流
  17. StreamReader sr = new StreamReader(strm);
  18. Console.WriteLine(sr.ReadToEnd());
  19. }
  20. }

3.WebBrowser控件

(1)使用WebBrowser控件
    使用WebBrowser控件非常简单,如下图:
技术分享技术分享
    其按钮的单击事件代码如下:
  1. private void button1_Click(object sender, EventArgs e)//按钮事件
  2. {
  3. this.webBrowser1.Navigate("http://www.baidu.com");//加载文档
  4. }
(2)WebBrowser控件常用属性、方法与事件
    WebBrowser控件常用的方法:Navigate():加载URI页面,GoBack():后退,GoForward():前进,Refresh():刷新,Stop():停止,GoHome():浏览主页。
    WebBrowser控件的常用属性:Document:获取当前正在浏览的文档,DocumentTitle:获取当前正在浏览的网页标题,StatusText:获取当前状态栏的文本,Url:获取当前正在浏览的网址的Uri,ReadyState:获取浏览的状态。
    WebBrowser控件的常用事件:DocumentCompleted:在WebBrowser控件完成加载文档时发生,XXXChanged:在XXX属性值更改时发生。
    注意:得到了Document属性就可以直接操作网页里的元素了!

4.网络工具类(URL、IP、DNS)

(1)Uri与UriBuilder
    Uri与UriBuilder类的主要区别是:Uri提供了很多只读属性,Uri对象被创建后就不能修改了;而UriBuilder类的属性较少,只允许构建一个完整的URI,这些属性可读写。
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. Uri uri = new Uri("http://www.baidu.com/s?wd=URI");
  6. //只读属性,Uri对象被创建后就不能修改了
  7. Console.WriteLine(uri.Query);//获取指定URI中包括的任何查询信息:?wd=URI
  8. Console.WriteLine(uri.AbsolutePath);//获取 URI 的绝对路径:/s
  9. Console.WriteLine(uri.Scheme);//获取此 URI 的方案名称:http
  10. Console.WriteLine(uri.Port);//获取此 URI 的端口号:80
  11. Console.WriteLine(uri.Host);//获取此实例的主机部分:www.baidu.com
  12. Console.WriteLine(uri.IsDefaultPort);//URI的端口值是否为此方案的默认值:true
  13. //创建UriBuilder对象,并给其属性赋值
  14. UriBuilder urib = new UriBuilder();
  15. urib.Host = uri.Host;
  16. urib.Scheme = uri.Scheme;
  17. urib.Path = uri.AbsolutePath;
  18. urib.Port = uri.Port;
  19. //测试
  20. UriTest(uri);//使用Uri对象
  21. UriTest(urib.Uri);//使用UriBuilder对象
  22. Console.Read();
  23. }
  24. //测试Uri对象
  25. static void UriTest(Uri uri)
  26. {
  27. Console.WriteLine("==============" + uri + "开始===============");
  28. Thread.Sleep(5000);
  29. HttpWebRequest httpweb = (HttpWebRequest)HttpWebRequest.Create(uri);
  30. HttpWebResponse res = (HttpWebResponse)httpweb.GetResponse();
  31. Stream stream = res.GetResponseStream();
  32. StreamReader strread = new StreamReader(stream);
  33. Console.WriteLine(strread.ReadToEnd());
  34. Console.WriteLine("======================完成===================\n\n\n\n");
  35. }
  36. }
(2)IPAddress、IPHostEntry 与Dns
    IPAddress类提供了对IP地址的转换、处理等功能。IPHostEntry类的实例对象中包含了Internet主机的相关信息。Dns类提供了一系列静态的方法,用于获取提供本地或远程域名等功能。
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. //IPAddress类提供了对IP地址的转换、处理等功能
  6. IPAddress ip =IPAddress.Parse("202.108.22.5");//百度的IP
  7. byte[] bit = ip.GetAddressBytes();
  8. foreach (byte b in bit)
  9. {
  10. Console.Write(b+" ");
  11. }
  12. Console.WriteLine("\n"+ip.ToString()+"\n\n");
  13. //IPHostEntry类的实例对象中包含了Internet主机的相关信息
  14. IPHostEntry iphe = Dns.GetHostEntry("www.microsoft.com");
  15. Console.WriteLine("www.microsoft.com主机DNS名:" + iphe.HostName);
  16. foreach (IPAddress address in iphe.AddressList)
  17. {
  18. Console.WriteLine("关联IP:"+address);
  19. }
  20. Console.WriteLine("\n");
  21. //Dns类提供了一系列静态的方法,用于获取提供本地或远程域名等功能
  22. iphe = Dns.GetHostEntry(Dns.GetHostName());
  23. Console.WriteLine("本地计算机名:" + iphe.HostName);
  24. foreach (IPAddress address in iphe.AddressList)
  25. {
  26. Console.WriteLine("关联IP:" + address);
  27. }
  28. Console.Read();
  29. }
  30. }
(3)解码与编码(Encoding)
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. Encoding utf8 = Encoding.UTF8;
  6. Encoding gb2312 = Encoding.GetEncoding("GB2312");
  7. //编码
  8. string test = "编码解码测试 ABCDabcd!";
  9. char[] source = test.ToCharArray();
  10. int len = utf8.GetByteCount(source, 0, test.Length);
  11. byte[] result = new byte[len];
  12. utf8.GetBytes(source, 0, test.Length, result, 0);
  13. foreach (byte b in result)
  14. {
  15. Console.Write("{0:X}", b);//16进制显示
  16. }
  17. Console.WriteLine();
  18. //解码
  19. Console.WriteLine(utf8.GetString(result));//输出字符串
  20. //得到所有系统编码
  21. EncodingInfo[] encodings = Encoding.GetEncodings();
  22. foreach (EncodingInfo e in encodings)
  23. {
  24. Console.WriteLine(e.Name);
  25. }
  26. //将URI地址进行编码
  27. Console.WriteLine(Uri.EscapeUriString("http://www.baidu.com/s?wd=李志伟"));
  28. //使用HttpUtility类进行编码与解码
  29. string temp = HttpUtility.UrlEncode("李志伟", gb2312);
  30. Console.WriteLine(temp + "-->" + HttpUtility.UrlDecode(temp, gb2312));
  31. Console.Read();
  32. }
  33. }

5.底层的网络协议类

(1)Socket
    Socket:实现 Berkeley 套接字接口。
    客户端代码:
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. Thread.Sleep(1000 * 2);
  6. Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  7. //服务器的IP和端口
  8. IPEndPoint ie = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
  9. client.Connect(ie);//连接服务端
  10. byte[] data = new byte[1024];
  11. int recv = client.Receive(data);//接收消息
  12. Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
  13. for (int i = 0; i < 20; i++)
  14. {
  15. client.Send(Encoding.UTF8.GetBytes(i + ":李志伟发送的消息!\n"));
  16. Console.WriteLine("发送消息数:" + i);
  17. Thread.Sleep(1000);
  18. }
  19. client.Shutdown(SocketShutdown.Both);//断开连接
  20. client.Close();
  21. Console.WriteLine("连接已断开!");
  22. Console.Read();
  23. }
  24. }
    服务端代码:
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
  6. Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  7. sock.Bind(ipep);//设置监听地址
  8. sock.Listen(10);//监听
  9. Console.WriteLine("已监听...");
  10. while (true)
  11. {
  12. Socket client = sock.Accept();//连接客户端
  13. Console.WriteLine("连接成功:" + client.RemoteEndPoint.ToString() + " -->" + client.LocalEndPoint.ToString());
  14. byte[] data = Encoding.UTF8.GetBytes("欢迎!!!");
  15. client.Send(data, data.Length, SocketFlags.None);//给客户端发送信息
  16. //不断的从客户端获取信息
  17. while (client.Connected)
  18. {
  19. data = new byte[1024];
  20. int recv = client.Receive(data);
  21. Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
  22. }
  23. client.Close();
  24. }
  25. sock.Close();
  26. }
  27. }
(2)NetworkStream、TcpClient与TcpListener
    NetworkStream:提供用于网络访问的基础数据流。TcpClient:为TCP网络服务提供客户端连接。TcpListener:从TCP网络客户端侦听连接。
    客户端代码:
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. Thread.Sleep(1000 * 2);
  6. for (int i = 0; i < 20; i++)
  7. {
  8. TcpClient tcpClient = new TcpClient();
  9. tcpClient.Connect(IPAddress.Parse("127.0.0.1"), 9999);
  10. Console.WriteLine(i + ":连接成功!");
  11. NetworkStream ns = tcpClient.GetStream();//打开流
  12. Byte[] sendBytes = Encoding.UTF8.GetBytes(i + ":李志伟发送的消息!\n");
  13. ns.Write(sendBytes, 0, sendBytes.Length);
  14. ns.Dispose();//释放流
  15. tcpClient.Close();//释放连接
  16. Console.WriteLine("已发送消息数:" + i);
  17. Thread.Sleep(1000);
  18. }
  19. Console.Read();
  20. }
  21. }
    服务端代码:
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. IPAddress ip = IPAddress.Parse("127.0.0.1");
  6. TcpListener listener = new TcpListener(ip, 9999);//IP地址与端口号
  7. listener.Start();// 开始侦听
  8. Console.WriteLine("已开始侦听...");
  9. while (true)
  10. {
  11. TcpClient client = listener.AcceptTcpClient();//接受挂起的连接请求
  12. Console.WriteLine("连接成功{0}-->{1}", client.Client.RemoteEndPoint.ToString(), client.Client.LocalEndPoint.ToString());
  13. NetworkStream ns = client.GetStream();
  14. StreamReader sread = new StreamReader(ns);
  15. Console.WriteLine(sread.ReadToEnd());
  16. }
  17. }
  18. }
    注意:TcpClient.Client属性就是Socket对象!
(3)UdpClient
    UdpClient:提供用户数据报 (UDP) 网络服务。
    发送端代码:
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. Thread.Sleep(1000 * 2);
  6. UdpClient udpClient = new UdpClient();
  7. udpClient.Connect(IPAddress.Parse("127.0.0.1"), 9999);//连接
  8. for (int i = 0; i < 20; i++)
  9. {
  10. Byte[] data = Encoding.UTF8.GetBytes(i + ":李志伟发送的消息!");
  11. udpClient.Send(data, data.Length);//发送数据
  12. Console.WriteLine("发送消息数:" + i);
  13. Thread.Sleep(1000);
  14. }
  15. udpClient.Close();
  16. Console.Read();
  17. }
  18. }
    接收端代码:
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. UdpClient udpClient = new UdpClient(9999);
  6. Console.WriteLine("已监听...");
  7. IPEndPoint RemoteIpEndPoint = null;
  8. while (true)//不断地接收数据
  9. {
  10. byte[] data = udpClient.Receive(ref RemoteIpEndPoint);//接收数据
  11. string str = Encoding.UTF8.GetString(data);
  12. Console.WriteLine("收到消息:" + str);
  13. Console.WriteLine("消息来源:" + RemoteIpEndPoint.ToString()+"\n");
  14. }
  15. }
  16. }
(4)SmtpClient
    SmtpClient类是用来发送邮件的,它在System.Web.Mail命名空间下。调用SmtpClient类的send(newMessage)方法,其中的参数newMessage是一个MailMessage对象,所以我们在调用send(newMessage)方法前,须实例化MailMessage类,然后对newMessage的属性设值。
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. SmtpClient smtp = new SmtpClient();
  6. MailMessage mail = new MailMessage("XXX@163.com", "XXXXXX@qq.com");
  7. //图像附件
  8. Attachment attach = new Attachment(@"F:\图片.jpg", MediaTypeNames.Image.Jpeg);
  9. //设置ContentId
  10. attach.ContentId = "pic";
  11. //ZIP附件
  12. Attachment attach2 = new Attachment(@"F:\图片.rar", "application/x-zip-compressed");
  13. mail.Attachments.Add(attach);//添加附件
  14. mail.Attachments.Add(attach2);//添加附件
  15. //标题和内容,注意设置编码,因为默认编码是ASCII
  16. mail.Subject = "你好";
  17. mail.SubjectEncoding = Encoding.UTF8;
  18. //HTML内容
  19. mail.Body = "<img src=\"cid:pic\"/><p>来自李志伟。</p>";
  20. mail.BodyEncoding = Encoding.UTF8;
  21. //指示改电子邮件内容是HTML格式
  22. mail.IsBodyHtml = true;
  23. //SMTP设置(根据邮箱类型设置,这里是163 Mail的SMTP服务器地址)
  24. smtp.Host = "smtp.163.com";
  25. smtp.UseDefaultCredentials = false;
  26. //某些SMTP服务器可能不支持SSL,会抛出异常
  27. smtp.EnableSsl = true;
  28. smtp.Credentials = new NetworkCredential("XXX@163.com", "password");
  29. smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
  30. //发送
  31. smtp.Send(mail);
  32. Console.WriteLine("=============OK=============");
  33. Console.Read();
  34. }
  35. }
-------------------------------------------------------------------------------------------------------------------------------




06.C#网络编程

标签:

原文地址:http://www.cnblogs.com/LiZhiW/p/4315911.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!