2024年2月21日发(作者:)
C#网络编程
1. WebClient类 .............................................................................................................................. 2
(1) WebClient类的主要方法 ................................................................................................ 2
(2) DownloadData()方法 ....................................................................................................... 2
(3) OpenRead()方法 ............................................................................................................... 2
(4) UploadData()方法 ........................................................................................................... 2
(5) 总结WebClient类 ........................................................................................................... 2
2. WebRequest类与WebResponse类 ............................................................................................ 2
(1) WebRequest类与WebResponse类简介 .......................................................................... 2
(2) 使用示例 ........................................................................................................................... 3
(3) WebRequest类与WebResponse类的子类(继承结构) .................................................. 3
(4) HttpWebRequest类与HttpWebResponse类使用示例 .................................................. 3
(5) 身份验证 ........................................................................................................................... 3
(6) 使用代理 ........................................................................................................................... 4
(7) 异步请求 ........................................................................................................................... 4
3. WebBrowser控件 ........................................................................................................................ 4
(1) 使用WebBrowser控件 ..................................................................................................... 4
(2) WebBrowser控件常用属性、方法与事件 ...................................................................... 5
4. 网络工具类(URL、IP、DNS) ..................................................................................................... 5
(1) Uri与UriBuilder ........................................................................................................... 5
(2) IPAddress、IPHostEntry 与Dns .................................................................................. 5
(3) 解码与编码(Encoding) ................................................................................................... 6
5. 底层的网络协议类 ..................................................................................................................... 7
(1) Socket ............................................................................................................................... 7
(2) NetworkStream、TcpClient与TcpListener ............................................................... 8
(3) UdpClient ......................................................................................................................... 8
(4) SmtpClient ....................................................................................................................... 9
作者:李志伟
时间:2014-02-07
ent类
(1)WebClient类的主要方法
DownloadXXX()方法:下载URI资源文件
OpenXXX()方法:打开URI资源流
UploadXXX()方法:上传资源到URI
(2)DownloadData()方法
class Program
{
static void Main(string[] args)
{
WebClient web = new WebClient();
byte[] temp = adData("");//下载URI资源文件
string Response = ing(temp);//解码
ine(Response);
();
}
}
(3)OpenRead()方法
class Program
{
static void Main(string[] args)
{
WebClient web = new WebClient();
Stream st = ad("");//打开URI资源流
StreamReader sr = new StreamReader(st);
string Response = End();
ine(Response);
();
}
}
(4)UploadData()方法
class Program
{
static void Main(string[] args)
{
WebClient web = new WebClient();
string str = "李志伟";
byte[] response =
Data("", es(str));
ine(ing(response));//解码
();
}
}
上传数据时出现问题,百度报错!这是因为没有权限。
(5)总结WebClient类
虽然WebClient类使用简单,但是其功能有限,特别是不能使用它提供身份验证证书。这样,在上传数据时问题就出现了,许多站点不接受没有身份验证的上传文件。这是由于WebClient类是非常一般的类,可以使用任意协议发送请求和接受响应(如:HTTP、FTP等)。但它不能处理特定于任何协议的任何特性,例如,专用于HTTP的cookie。如果想利用这些特性就需要使用WebRequest类与WebResponse类为基类的一系列类。
uest类与WebResponse类
(1)WebRequest类与WebResponse类简介
WebRequest类与WebResponse类是抽象类,其子类对象代表某个特定URI协议的请求对象或响应对象。调用()方法得到WebResponse对象。调用WebResponse对象的GetResponse()方法得到WebResponse对象。
(2)使用示例
class Program
{
static void Main(string[] args)
{
WebRequest req = ("");//得到请求对象
WebResponse res = ponse();//得到相应对象
Stream strm = ponseStream();//得到相应数据流
StreamReader sr = new StreamReader(strm);
ine(End());
();
}
}
(3)WebRequest类与WebResponse类的子类(继承结构)
FileWebRequestFtpWebRequestWebRequestHttpWebRequestPackWebRequestFileWebResponseFtpWebResponseWebResponseHttpWebResponsePackWebResponse提供 WebResponse 类的 HTTP 特定的实现。提供 WebRequest 类的 HTTP 特定的实现。提供 WebRequest 类的文件系统实现封装文件传输协议 (FTP) 服务器对请求的响应。表示 PackWebRequest 的响应。提供 WebResponse 类的文件系统实现封装文件传输协议 (FTP) 服务器对请求的响应。表示 PackWebResponse 的响应。
(4)HttpWebRequest类与HttpWebResponse类使用示例
class Program
{
static void Main(string[] args)
{
string uri = "";
HttpWebRequest httpRe = (HttpWebRequest)(uri);
HttpWebResponse httpRes = (HttpWebResponse)ponse();
Stream strm = ponseStream();//得到相应数据流
StreamReader sr = new StreamReader(strm);
ine(End());
();
}
}
这里以HTTP协议为例使用了对应了类,其他协议的类的使用方法与此类似。
(5)身份验证
如果需要把身份验证证书附带在请求中,就使用WebRequest类中的Credentials属性。
class Program
{
static void Main(string[] args)
{
WebRequest req = ("");//得到请求对象
NetworkCredential cred = new NetworkCredential("userName", "password");
tials = cred;//调用GetResponse()之前赋值
WebResponse res = ponse();//得到相应对象
Stream strm = ponseStream();//得到相应数据流
StreamReader sr = new StreamReader(strm);
ine(End());
();
}
}
(6)使用代理
使用代理服务器需要用到WebRequest类中的Proxy属性,以及WebProxy对象。
class Program
{
static void Main(string[] args)
{
WebRequest req = ("");//得到请求对象
NetworkCredential cred = new NetworkCredential("userName", "password","Domain");
WebProxy wp = new WebProxy("192.168.1.100", true);//设置代理服务器地址
tials = cred;//调用GetResponse()之前赋值
= wp;//调用GetResponse()之前赋值
WebResponse res = ponse();//得到相应对象
Stream strm = ponseStream();//得到相应数据流
StreamReader sr = new StreamReader(strm);
ine(End());
();
}
}
(7)异步请求
若需要使用异步请求,就可以使用BeginGetRequestStream()、EndGetRequestStream()与BeginGetResponse()、EndGetResponse()方法。使用异步请求就不需要等待请求的响应,主线程不必阻塞可以直接向下执行。示例如下:
class Program
{
static void Main(string[] args)
{
WebRequest req = ("");//得到请求对象
etResponse(new AsyncCallback(Callback), req);//得到相应对象
ine("异步请求已发送...");
();
}
//回调函数
private static void Callback(IAsyncResult ar)
{
(5000);//休眠5秒
WebRequest req = (WebRequest)tate;
WebResponse res = Response(ar);
Stream strm = ponseStream();//得到相应数据流
StreamReader sr = new StreamReader(strm);
ine(End());
}
}
wser控件
(1)使用WebBrowser控件
使用WebBrowser控件非常简单,如下图:
其按钮的单击事件代码如下:
private void button1_Click(object sender, EventArgs e)//按钮事件
{
te("");//加载文档
}
(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,这些属性可读写。
class Program
{
static void Main(string[] args)
{
Uri uri = new Uri("/s?wd=URI");
//只读属性,Uri对象被创建后就不能修改了
ine();//获取指定URI中包括的任何查询信息:?wd=URI
ine(tePath);//获取 URI 的绝对路径:/s
ine();//获取此 URI 的方案名称:http
ine();//获取此 URI 的端口号:80
ine();//获取此实例的主机部分:
ine(ultPort);//URI的端口值是否为此方案的默认值:true
//创建UriBuilder对象,并给其属性赋值
UriBuilder urib = new UriBuilder();
= ;
= ;
= tePath;
= ;
//测试
UriTest(uri);//使用Uri对象
UriTest();//使用UriBuilder对象
();
}
//测试Uri对象
static void UriTest(Uri uri)
{
ine("==============" + uri + "开始===============");
(5000);
HttpWebRequest httpweb = (HttpWebRequest)(uri);
HttpWebResponse res = (HttpWebResponse)ponse();
Stream stream = ponseStream();
StreamReader strread = new StreamReader(stream);
ine(End());
ine("======================完成===================nnnn");
}
}
(2)IPAddress、IPHostEntry 与Dns
IPAddress类提供了对IP地址的转换、处理等功能。IPHostEntry类的实例对象中包含
了Internet主机的相关信息。Dns类提供了一系列静态的方法,用于获取提供本地或远程域名等功能。
class Program
{
static void Main(string[] args)
{
//IPAddress类提供了对IP地址的转换、处理等功能
IPAddress ip =("202.108.22.5");//百度的IP
byte[] bit = ressBytes();
foreach (byte b in bit)
{
(b+" ");
}
ine("n"+ng()+"nn");
//IPHostEntry类的实例对象中包含了Internet主机的相关信息
IPHostEntry iphe = tEntry("");
ine("主机DNS名:" + me);
foreach (IPAddress address in sList)
{
ine("关联IP:"+address);
}
ine("n");
//Dns类提供了一系列静态的方法,用于获取提供本地或远程域名等功能
iphe = tEntry(tName());
ine("本地计算机名:" + me);
foreach (IPAddress address in sList)
{
ine("关联IP:" + address);
}
();
}
}
(3)解码与编码(Encoding)
class Program
{
static void Main(string[] args)
{
Encoding utf8 = 8;
Encoding gb2312 = oding("GB2312");
//编码
string test = "编码解码测试 ABCDabcd!";
char[] source = Array();
int len = eCount(source, 0, );
byte[] result = new byte[len];
es(source, 0, , result, 0);
foreach (byte b in result)
{
("{0:X}", b);//16进制显示
}
ine();
//解码
ine(ing(result));//输出字符串
//得到所有系统编码
EncodingInfo[] encodings = odings();
foreach (EncodingInfo e in encodings)
{
ine();
}
//将URI地址进行编码
ine(UriString("/s?wd=李志伟"));
//使用HttpUtility类进行编码与解码
string temp = ode("李志伟", gb2312);
ine(temp + "-->" + ode(temp, gb2312));
();
}
}
5.底层的网络协议类
(1)Socket
Socket:实现 Berkeley 套接字接口。
客户端代码:
class Program
{
static void Main(string[] args)
{
(1000 * 2);
Socket client = new Socket(etwork,
, );
//服务器的IP和端口
IPEndPoint ie = new IPEndPoint(("127.0.0.1"), 9999);
t(ie);//连接服务端
byte[] data = new byte[1024];
int recv = e(data);//接收消息
ine(ing(data, 0, recv));
for (int i = 0; i < 20; i++)
{
(es(i + ":李志伟发送的消息!n"));
ine("发送消息数:" + i);
(1000);
}
wn();//断开连接
();
ine("连接已断开!");
();
}
}
服务端代码:
class Program
{
static void Main(string[] args)
{
IPEndPoint ipep = new IPEndPoint(("127.0.0.1"), 9999);
Socket sock = new Socket(etwork,
, );
(ipep);//设置监听地址
(10);//监听
ine("已监听...");
while (true)
{
Socket client = ();//连接客户端
ine("连接成功:" + ng() + " -->" +
ng());
byte[] data = es("欢迎!!!");
(data, , );//给客户端发送信息
//不断的从客户端获取信息
while (ted)
{
data = new byte[1024];
int recv = e(data);
ine(ing(data, 0, recv));
}
();
}
();
}
}
(2)NetworkStream、TcpClient与TcpListener
NetworkStream:提供用于网络访问的基础数据流。TcpClient:为TCP网络服务提供客户端连接。TcpListener:从TCP网络客户端侦听连接。
客户端代码:
class Program
{
static void Main(string[] args)
{
(1000 * 2);
for (int i = 0; i < 20; i++)
{
TcpClient tcpClient = new TcpClient();
t(("127.0.0.1"), 9999);
ine(i + ":连接成功!");
NetworkStream ns = eam();//打开流
Byte[] sendBytes = es(i + ":李志伟发送的消息!n");
(sendBytes, 0, );
e();//释放流
();//释放连接
ine("已发送消息数:" + i);
(1000);
}
();
}
}
服务端代码:
class Program
{
static void Main(string[] args)
{
IPAddress ip = ("127.0.0.1");
TcpListener listener = new TcpListener(ip, 9999);//IP地址与端口号
();// 开始侦听
ine("已开始侦听...");
while (true)
{
TcpClient client = TcpClient();//接受挂起的连接请求
ine("连接成功{0}-->{1}",
ng(),
ng());
NetworkStream ns = eam();
StreamReader sread = new StreamReader(ns);
ine(End());
}
}
}
注意:属性就是Socket对象!
(3)UdpClient
UdpClient:提供用户数据报 (UDP) 网络服务。
发送端代码:
class Program
{
static void Main(string[] args)
{
(1000 * 2);
UdpClient udpClient = new UdpClient();
t(("127.0.0.1"), 9999);//连接
for (int i = 0; i < 20; i++)
{
Byte[] data = es(i + ":李志伟发送的消息!");
(data, );//发送数据
ine("发送消息数:" + i);
(1000);
}
();
();
}
}
接收端代码:
class Program
{
static void Main(string[] args)
{
UdpClient udpClient = new UdpClient(9999);
ine("已监听...");
IPEndPoint RemoteIpEndPoint = null;
while (true)//不断地接收数据
{
byte[] data = e(ref RemoteIpEndPoint);//接收数据
string str = ing(data);
ine("收到消息:" + str);
ine("消息来源:" + ng()+"n");
}
}
}
(4)SmtpClient
SmtpClient类是用来发送邮件的,它在命名空间下。调用SmtpClient类的send(newMessage)方法,其中的参数newMessage是一个MailMessage对象,所以我们在调用send(newMessage)方法前,须实例化MailMessage类,然后对newMessage的属性设值。
class Program
{
static void Main(string[] args)
{
SmtpClient smtp = new SmtpClient();
MailMessage mail = new MailMessage("XXX@", "XXXXXX@");
//图像附件
Attachment attach = new Attachment(@"F:图片.jpg", );
//设置ContentId
tId = "pic";
//ZIP附件
Attachment attach2 =
new Attachment(@"F:图片.rar", "application/x-zip-compressed");
(attach);//添加附件
(attach2);//添加附件
//标题和内容,注意设置编码,因为默认编码是ASCII
t = "你好";
tEncoding = 8;
//HTML内容
= "
来自李志伟。
";coding = 8;
//指示改电子邮件内容是HTML格式
Html = true;
//SMTP设置(根据邮箱类型设置,这里是163 Mail的SMTP服务器地址)
= "";
aultCredentials = false;
//某些SMTP服务器可能不支持SSL,会抛出异常
Ssl = true;
tials = new NetworkCredential("XXX@", "password");
ryMethod = k;
//发送
(mail);
ine("=============OK=============");
();
}
}


发布评论