第22章 网络编程

一、System.Net命名空间:对网络进行操作

1、Dns类:检索主机信息

 

代码:

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == string.Empty)
            {
                MessageBox.Show("请输入主机地址!");
            }
            else
            {
                textBox2.Text = string.Empty;
                IPAddress[] ips = Dns.GetHostAddresses(textBox1.Text);  //获取主机IP地址
                foreach (IPAddress ip in ips)
                {
                    textBox2.Text = ip.ToString();
                }

                textBox3.Text = Dns.GetHostName();  //获取本地计算机名

                textBox4.Text = Dns.GetHostByName(Dns.GetHostName()).HostName; //本地的DNS主机名
                //DNS:域名系统 (Domain Name System) 的缩写
               
            }
        }

 

2.IPAddress类:IP网络上的地址

 

代码:

            IPAddress[] ips = Dns.GetHostAddresses(textBox1.Text); //获取IP地址
            foreach (IPAddress ip in ips)
            {
                label2.Text = "网络协议地址:" + ip.Address + "/nIP地址的地址族:" + ip.AddressFamily + "/n是否IPv6链接本地地址:" + ip.IsIPv6LinkLocal;
            }

 

3.IPEndPoint类:连接主机所需的端口号(网络端点)

 

代码:

        private void button1_Click(object sender, EventArgs e)
        {
            IPEndPoint IPEPoint = new IPEndPoint(IPAddress.Parse(textBox1.Text), 80);//实例化网络端点
            label2.Text = "IP地址:" + IPEPoint.Address.ToString() + "/n端口号:" + IPEPoint.Port;
        }

 

4.WebClient类:向网址发送数据,接收数据

 

            WebClient wclient = new WebClient(); //实例化WebClient对象
            wclient.BaseAddress = textBox1.Text; //设置WebClient基于的网址
            wclient.Encoding = Encoding.UTF8;    //指定下载字符串的编码方式
            //为WebClient类对象添加标头
            wclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            //使用OpenRead方法获取指定网站的数据,并保存到Stream流中
            Stream stream = wclient.OpenRead(textBox1.Text);
            //使用流Stream声明一个流读取变量sreader
            StreamReader sreader = new StreamReader(stream);
            string str = string.Empty;//声明一个变量,用来保存一行从WebCliecnt下载的数据
            //循环读取从指定网站获得的数据
            while ((str = sreader.ReadLine()) != null)
            {
                richTextBox1.Text += str + "/n";
            }
            //调用WebClient对象的DownloadFile方法将指定网站的内容保存到文件中
            wclient.DownloadFile(textBox1.Text, DateTime.Now.ToFileTime() + ".txt");
            MessageBox.Show("保存到文件成功");

 

5.WebRequest类:获取网页请求信息

   WebResponse类:获取网页内容(调用WebRequest对象的GetResponse方法实例化WebResponse对象)

 

 

            richTextBox1.Text = string.Empty;
            //实例化一个WebRequest对象
            WebRequest webrequest = WebRequest.Create(textBox1.Text);
            //设置用于对Internet资源请求进行身份验证的网络凭据
            webrequest.Credentials = CredentialCache.DefaultCredentials;
            //调用WebRequest对象的各种属性获取WebRequest请求的相关信息
            richTextBox1.Text = "请求数据的内容长度:" + webrequest.ContentLength;
            richTextBox1.Text += "/n该请求的协议方法:" + webrequest.Method;
            richTextBox1.Text += "/n访问Internet的网络代理:" + webrequest.Proxy;
            richTextBox1.Text += "/n与该请求关联的Internet URI:" + webrequest.RequestUri;
            richTextBox1.Text += "/n超时时间:" + webrequest.Timeout;
            //调用WebRequest对象的GetResponse方法实例化一个WebResponse对象
            WebResponse webresponse = webrequest.GetResponse();
            //获取WebResponse响应的Internet资源的URI
            richTextBox1.Text += "/n响应该请求的Internet URI:" + webresponse.ResponseUri;
            //调用WebResponse对象的GetResponseStream方法返回数据流
            Stream stream = webresponse.GetResponseStream();
            //使用创建的Stream对象创建一个StreamReader流读取对象
            StreamReader sreader = new StreamReader(stream);
            //读取流中的内容,并显示在RichTextBox控件中
            richTextBox1.Text += "/n" + sreader.ReadToEnd();
            sreader.Close();
            stream.Close();
            webresponse.Close();

 

 

二、System.Net.Sockets命名空间:制作Sockets网络应用程序的相关类

1.Socket类

 

代码:

        private static Socket ConnectSocket(string server, int port)
        {
            Socket socket = null;                    //实例化Socket对象,并初始化为空
            IPHostEntry iphostentry = null;          //实例化IPHostEntry对象(包含了Internet主机的相关信息),并初始化为空
            iphostentry = Dns.GetHostEntry(server);  //获得主机信息
            //循环遍历得到的IP地址列表
            foreach (IPAddress address in iphostentry.AddressList)
            {
                //第一步:使用指定的IP地址和端口号实例化IPEndPoint对象
                IPEndPoint IPEPoint = new IPEndPoint(address, port);
                //第二步:使用Socket的构造函数实例化一个Socket对象,以便用来连接远程主机
                Socket newSocket = new Socket(IPEPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                //IPEPoint.AddressFamily网络协议(IP)地址族,SocketType.Stream 套接的字段流类型,ProtocolType.Tcp传输控制协议Tcp

                newSocket.Connect(IPEPoint);          //调用Connect方法连接远程主机
                if (newSocket.Connected)              //判断远程连接是否连接
                {
                    socket = newSocket;
                    break;
                }
                else
                {
                    continue;
                }
            }
            return socket;
        }


        //获取指定服务器的主页面内容
        private static string SocketSendReceive(string server, int port)
        {
            string request = "GET/HTTP/1.1/n主机:" + server + "/n连接:关闭/n";
            Byte[] btSend = Encoding.ASCII.GetBytes(request); //将一组字符编码为一个字节序列
            Byte[] btReceived = new Byte[256];//定义长度为256的定长字节数组
            //调用自定义方法ConnectSocket,使用指定的服务器名和端口号实例化一个Socket对象
            Socket socket = ConnectSocket(server, port);
            if (socket == null)
                return ("连接失败!");
            //将请求发送到连接的服务器
            socket.Send(btSend, btSend.Length, 0);
            int intContent = 0;
            string strContent = server + "上的默认页面内容:/n";
            do
            {
                //从绑定的Socket接收数据
                intContent = socket.Receive(btReceived, btReceived.Length, 0);
                //btReceived 接收数据的位置,btReceived.Length 要接收的字节数
                //将接收到的数据转换为字符串类型
                strContent += Encoding.ASCII.GetString(btReceived, 0, intContent);
            }
            while (intContent > 0);
            return strContent;
        }


        private void button1_Click(object sender, EventArgs e)
        {
            string server = textBox1.Text;               //指定主机名
            int port = Convert.ToInt32(textBox2.Text);   //指定端口号
            //调用自定义方法SocketSendReceive获取指定主机的主页面内容
            string strContent = SocketSendReceive(server, port);
            MessageBox.Show(strContent);
        }

 

 

2.TcpClient类和TcpListener类

    内容

 

3.UdpClient类

三、System.Net.Mail命名空间

1、MailMessage类:主要用于指定邮件的发送地址,收件人地址,邮件正文和附件

2、Attachment类:邮件附件

3、SmtpClient类:发送邮件

 

示例:

            //注意:测试的时候要关闭本机防火墙;不要使用QQ邮箱
            string file = "邮件测试.txt";
            MailAddress from = new MailAddress("chyenao20@163.com");   //设置邮件发送人
            MailAddress to = new MailAddress("litaoxf123@163.com");     //设置邮件接收人
            MailMessage message = new MailMessage(from,to);        //实例化一个MaileMessage类对象
            message.Subject = "邮件测试";                          //设置发送邮件的主题
            message.Body = "邮件正文";                             //设置发送邮件的内容

            //为要发送的邮件创建附件信息(file为附件文件名)
            Attachment myAttachment = new Attachment(file, System.Net.Mime.MediaTypeNames.Application.Octet);
            //为附件添加时间信息
            System.Net.Mime.ContentDisposition disposition = myAttachment.ContentDisposition;
            disposition.CreationDate = System.IO.File.GetCreationTime(file); //为附件添加邮件创建时间
            disposition.ModificationDate = System.IO.File.GetLastWriteTime(file); //为附件添加邮件修改时间
            disposition.ReadDate = System.IO.File.GetLastAccessTime(file);//为附件添加邮件读取时间
            message.Attachments.Add(myAttachment);             //将创建的附件添加到邮件中

            //实例化SmtpClient邮件发送类对象(smtp.163.com为SMTP服务器)
            SmtpClient client = new SmtpClient("smtp.163.com", 25);
            //设置用于验证发件人身份的凭据(发件人的账号,密码)
            client.Credentials = new System.Net.NetworkCredential("chyenao20@163.com", "lt******");
            //发送邮件
            client.Send(message);
            MessageBox.Show("发送成功");

 

 

实践:

1。创建WEB页面浏览器

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "")
            {
                Uri address = new Uri(textBox1.Text);
                webBrowser1.Url = address;   //webBrowser控件
            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)   //判断是否按下Enter键
            {
                if (textBox1.Text != "")
                {
                    button1_Click(sender, e);
                }
            }
        }

 

2。设计点对点聊天程序

3。电子邮件的发送和接收

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tiz198183

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值