《C#高级编程》读书笔记(十八):网络
1,网络
在网络环境下,我们最感兴趣的两个命名空间是 System.Net 和 System.Net.Sockets。 System.Net 名称空间通常与较高层的操作有关,例如下载和上传文件,使用 HTTP 和其他协议进行 Web 请求;而 System.Net.Sockets 名称空间包含的类通常与较低层的操作有关。如果要直接使用套接字或 TCP/IP 之类的协议,这个名称空间中的类就非常有用。
2,HttpClient类
HttpClient 类用于发送 HTTP 请求,接收请求的响应。它在 System.Net.Http 名称空间中。
static void Main(string[] args) { Console.WriteLine("In main before call to GetData!"); GetData(); Console.WriteLine("Back in main after call to GetData!"); Console.ReadKey(); } private static async void GetData() { HttpClient httpClient = new HttpClient(); HttpResponseMessage response = null; response = await httpClient.GetAsync( "http://services.odata.org/northwind/northwind.svc/Regions"); if (response.IsSuccessStatusCode) { Console.WriteLine("Response Status Code:" +response.StatusCode +" " + response.ReasonPhrase); string responseBodyAsText = response .Content .ReadAsStringAsync() .Result; Console.WriteLine("Received payload of " +responseBodyAsText.Length + " characters"); } }
3,把输出结果显示为HTML页面
用WebBrowser控件实现:
using System.Windows.Forms; namespace Browser { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char) 13) { webBrowser1.Navigate(textBox1.Text); } } } }
4,实用工具类
1)URI
Uri和UriBuilder 是 System 名称空间中的两个类,他们都用于表示 URI。UriBuilder 类允许把给定的字符串当做URI的组成部分,从而构建一个URI;而 Uri 类允许分析、组合和比较URI。
static void Main(string[] args) { Uri MSPage = new Uri("http://www.Microsoft.com/SomeFolder/SomeFile.htm?Order=true"); Console.WriteLine(MSPage.Query); Console.WriteLine(MSPage.AbsolutePath); Console.WriteLine(MSPage.Scheme); Console.WriteLine(MSPage.Port); Console.WriteLine(MSPage.Host); Console.WriteLine(MSPage.IsDefaultPort); Console.ReadKey(); }
UriBuilder MSPage = new UriBuilder("http","www.microsoft",80,"SomeFolder/SomeFile.htm");
2)IP 地址和 DNS 名称
IPAddress ipAddress = IPAddress.Parse("234.56.78.9"); string ipString = ipAddress.ToString(); Console.WriteLine(ipString); Console.ReadKey();
IPHostEntry wroxHost = Dns.GetHostEntry("www.wrox.com"); IPHostEntry wroxHostCopy = Dns.GetHostEntry("208.215.179.178");
5,较低层的协议
Tcp类:TcpSend和TcpReceive示例
using System; using System.IO; using System.Net.Sockets; using System.Windows.Forms; namespace TcpSend { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { TcpClient tcpClient = new TcpClient(textBox1.Text,int.Parse(textBox2.Text)); NetworkStream ns = tcpClient.GetStream(); FileStream fs = File.Open("Form1.cs", FileMode.Open); int data = fs.ReadByte(); while (data != -1) { ns.WriteByte((byte)data); data = fs.ReadByte(); } fs.Close(); ns.Close(); tcpClient.Close(); } } }
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using System.Windows.Forms; namespace TcpReceive { public partial class Form1 : Form { 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(); } public void UpdateDisplay(string text) { txtDisplay.Text = text; } protected delegate void UpdateDisplayDelegate(string text); } }
Socket类
Socket类提供了网络编程中最高级的控制。
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using System.Windows.Forms; namespace TcpReceive { public partial class Form1 : Form { public Form1() { InitializeComponent(); Thread thread = new Thread(new ThreadStart(Listen)); thread.Start(); } 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), result); socket.Close(); listener.Close(); } public void UpdateDisplay(string text) { txtDisplay.Text = text; } protected delegate void UpdateDisplayDelegate(string text); } }