第13章 网络应用编程技术

来源:互联网 发布:mac air散热 编辑:程序博客网 时间:2024/06/06 23:53

  • 1 网络编程基础
    • 11 计算机网络概述
    • 12 计算机网络的通信协议
    • 13 SystemNet 概述
  • 2 Socket 编程
    • 21 Socket 编程概述
    • 22 TCP 应用编程
    • 23 UDP 应用编程
  • 3 Email和FTP应用编程
    • 31 Email 的发送
    • 32 Email 的接收
    • 33 FTP 的下载

13.1 网络编程基础

13.1.1 计算机网络概述

13.1.2 计算机网络的通信协议

13.1.3 System.Net 概述

1. IPAddress 类

对 IP 地址的转化、处理等功能

// IPAddress.Parse 可将 IP 地址字符串转换为 IPAddress 实例IPAddress ip = IPAddress.Parse("192.168.1.1");

2. Dns 类

DNS功能

    GetHostAddress()
提取主机的IP地址,返回一个IPAddress类型的数组
IPAddress[] ip = new Dns.GetHostAddress("www.baidu.com");
    GetHostName()
返回主机名
string hostname = Dns.GetHostName();

3. IPHostEntry 类

网络主机的相关信息

  • AddressList,获取或设置与主机关联的 IP 地址列表
IPAddress[] ip = Dns.GetHostEntry("www.baidu.com").AddressList;
  • HostName
4. IPEndPoint 类
端点
ipadress+port
public IPEndPoint(IPAddress, int);

5. WebClient
提供向URI标识的资源发送数据以及从这些资源接收数据的公共方法

方法 说明 DownloadData() 从服务器下载数据并返回Byte数组 DownloadFile() 从服务器将数据下载到本地文件 DownloadString() 从服务器下载 String 并返回 String OpenRead() 从服务器以 Stream 形式返回数据 UploadFile() 将本地文件发送到服务器 UploadData() 将字节数组发送到服务器 UploadString() 将 String 发送到服务器 UploadValues() 将 NameValueCollection 发送到服务器 UploadWrite() 使用 Stream 把数据发送到服务器
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Net;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace Web_CS{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void Form1_Load(object sender, EventArgs e)        {        }        private void btnDown_Click(object sender, EventArgs e)        {            WebClient client = new WebClient();            client.DownloadFile(txtUri.Text, txtPath.Text + "\\" + txtName.Text);            lblShow.Text = "下载成功!";        }    }}

13.2 Socket 编程

13.2.1 Socket 编程概述

1. Socket 工作原理

  • 服务器监听
  • 客户端请求
  • 连接确认

2. Socket 类

// 构造函数public Socket(AddressFamily a, SocketType s, ProtocolType p);

3. 面向连接的套接字

@TCP// ServerSocket()---->Bind()---->Listen()---->Accept()---->Receive()---->Send()---->Close()                                        |          |              |          |// Client                               |          |              |          |Socket()---------------------------->Connect()--->Send()------->Receive()->Close()

Listen方法执行之后,服务器已经做好了接收任何客户连接的准备,这是用Accept方法完成的,当有新客户进行连接时,该方法就返回一个新的套接字描述符。程序执行到Accept方法时会处于阻塞状态,直到有客户机请求连接,在接受客户机连接之后,客户机和服务器就可用Receive方法和Send方法开始传递数据。

4. 无连接的套接字

@UDP// ServerSocket()---->Bind()---->ReceiveFrom()---->SendTo()---->Close()               |           |                |             |// Client      |           |                |             |Socket()---->Bind()---->SendTo()--------->ReceiveFrom()->Close()

13.2.2 TCP 应用编程

1. TcpListener 类
用于监听和接收传入的连接请求

// 构造函数TcpListener(IPEndPoint iep);TcpListener(IPAddress localAddr, int port);

2. TcpClient 类

  • AcceptTcpSocket
  • AcceptTcpClient
  • Start
  • Stop

构造函数

TcpClient tcpClient = new TcpClient();tcpClient.Connect("www.baidu.com", 34124);
  • TcpClient():自动选择客户端未使用的ip地址和port
  • TcpClient(AddressFamily family):同上,规定了协议
  • TcpClient(IPEndPoint iep):知道了主机ipport
  • TcpClient(string hostname, int port):最方便,不需要使用connection方法

3. 同步 TCP 应用编程

Server

using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading.Tasks;namespace ConsoleAS{    class Program    {        static void Main(string[] args)        {            TcpListener server = null;            Console.Write("请输入监听的端口号:");            string strPort = Console.ReadLine();            try            {                int port = Convert.ToInt32(strPort);                IPEndPoint listenPort = new IPEndPoint(IPAddress.Any, port);                server = new TcpListener(listenPort);                server.Start();                Byte[] bytes = new Byte[256];                String data = null;                while (true)                {                    Console.Write("服务已启动.....");                    TcpClient client = server.AcceptTcpClient();                    Console.Write("已连接");                    data = null;                    NetworkStream stream = client.GetStream();                    int i;                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)                    {                        data = System.Text.Encoding.UTF8.GetString(bytes, 0, i);                        Console.WriteLine("接收消息:{0}", data);                        Console.Write("发送消息:");                        data = Console.ReadLine();                        byte[] msg = System.Text.Encoding.UTF8.GetBytes(data);                        stream.Write(msg, 0, msg.Length);                    }                    client.Close();                }            }            catch (Exception e)            {                Console.WriteLine(e.Message);            }            finally            {                server.Stop();            }            Console.WriteLine("\n按任意键退出!");            Console.Read();        }    }}

Client

using System;using System.Collections.Generic;using System.Linq;using System.Net.Sockets;using System.Text;using System.Threading.Tasks;namespace ConsoleBS{    class Program    {        static TcpClient client = null;        static NetworkStream stream = null;        static void Main(string[] args)        {            Console.Write("请输入服务器ip地址:");            string strIP = Console.ReadLine();            Console.Write("请输入服务器监听的端口号:");            string strPort = Console.ReadLine();            int port = Convert.ToInt32(strPort);            Connect(strIP, port);            do            {                Console.Write("发送消息:");                string message = Console.ReadLine();                SentAndReceived(message);                Console.WriteLine("是否继续发送消息?(Y/N)");                if (Console.ReadLine().ToUpper() == "N")                    break;            } while (true);            if (stream != null)                stream.Close();            if (client != null)                client.Close();            Console.WriteLine("\n按任意键退出...");            Console.Read();        }        static void Connect(string server, int port)        {            try            {                client = new TcpClient(server, port);            }            catch (Exception e)            {                Console.WriteLine(e.Message);            }        }        static void SentAndReceived(string message)        {            Byte[] data = System.Text.Encoding.UTF8.GetBytes(message);            stream = client.GetStream();            stream.Write(data, 0, data.Length);            data = new Byte[1024];            String reponseData = String.Empty;            int bytes = stream.Read(data, 0, data.Length);            reponseData = System.Text.Encoding.UTF8.GetString(data, 0, bytes);            Console.WriteLine("接收消息:{0}", reponseData);        }    }}

13.2.3 UDP 应用编程

无连接是指,在正式通信之前不必先与对方建立连接,不管对方状态如何就直接发送过去。

只提供 UdpClient 类,用于发送和接收无连接的UDP数据报。
- 使用hostnameport创建 UdpClient 实例
- 创建不带参数的 UdpClient类的实例,调用Connect方法指定默认远程主机
- Send方法返回数据的长度
- Receive方法将接收到的数据作为字节数组返回

组播地址
224.0.0.0~239.255.255.255


13.3 EmailFTP应用编程

13.3.1 Email 的发送

13.3.2 Email 的接收

13.3.3 FTP 的下载

未完待续···

0 0
原创粉丝点击