System.Net基础类库和示例

System.Net基础类库和示例

System.Net 是什么库?

System.Net 是 .NET Framework 和 .NET Core 中提供网络通信的基础接口和类库之一,它包含了许多不同的类和接口,可以提供丰富的网络操作功能。

System.Net 中有哪些类和接口?

System.Net 中的类和接口可以分为高层次类和较低级别类两类。

高层次类包括 WebClient、HttpWebRequest、FtpWebRequest、SmtpClient 等。

WebClient:用于 HTTP/HTTPS 协议的下载与上传,如从远程服务器获取 Web 页面或文件。示例代码:

WebClient client = new WebClient();
string downloadString = client.DownloadString("https://www.example.com");
Console.WriteLine(downloadString);

HttpWebRequest:提供了更细粒度的 HTTP 操作控制,可以设置请求头、请求方法、代理等属性。示例代码:

CodeHttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.example.com/index.html");
request.Method = "GET";
request.ContentType = "text/html";
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string content = reader.ReadToEnd();
Console.WriteLine(content);

FtpWebRequest:用于 FTP 协议的上传与下载。示例代码:

CodeFtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/test.txt");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
byte[] fileContents = Encoding.UTF8.GetBytes("This is a test file.");
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();

SmtpClient:用于 SMTP 协议的发送邮件。示例代码:

CodeMailMessage mail = new MailMessage();
mail.From = new MailAddress("sender@example.com");
mail.To.Add("recipient@example.com");
mail.Subject = "Test Mail";
mail.Body = "This is a test message.";
SmtpClient client = new SmtpClient("smtp.example.com", 25);
client.Credentials = new NetworkCredential("username", "password");
client.EnableSsl = true;
client.Send(mail);
Console.WriteLine("Mail sent successfully.");

较低级别类包括 Socket、TcpClient、UdpClient、WebRequest 等。

Socket:提供了访问 TCP、UDP、RAW、IP 等协议的网络通信功能。示例代码:

byte[] buffer = new byte[1024];
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect("www.example.com", 80);
string request = "GET /index.html HTTP/1.1rnHost: www.example.comrnrn";
socket.Send(Encoding.UTF8.GetBytes(request));
int count = socket.Receive(buffer);
string response = Encoding.UTF8.GetString(buffer, 0, count);
Console.WriteLine(response);

TcpClient:用于访问 TCP 协议的连接。示例代码:

TcpClient client = new TcpClient("www.example.com", 80);
Stream stream = client.GetStream();
string request = "GET /index.html HTTP/1.1rnHost: www.example.comrnrn";
byte[] buffer = Encoding.UTF8.GetBytes(request);
stream.Write(buffer, 0, buffer.Length);
buffer = new byte[1024];
int count = stream.Read(buffer, 0, buffer.Length);
string response = Encoding.UTF8.GetString(buffer, 0, count);
Console.WriteLine(response);

UdpClient:用于访问 UDP 协议的连接。示例代码:

UdpClient client = new UdpClient();
client.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.100"), 1234));
string message = "Hello World";
byte[] data = Encoding.UTF8.GetBytes(message);
client.Send(data, data.Length);
IPEndPoint remoteEP = null;
data = client.Receive(ref remoteEP);
string response = Encoding.UTF8.GetString(data);
Console.WriteLine(response);

WebRequest:提供了一个通用的请求/响应机制,可以通过不同的协议(HTTP、FTP、FILE 等)下载或上传数据。示例代码:

WebRequest request = WebRequest.Create("https://www.example.com/index.html");
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string content = reader.ReadToEnd();
Console.WriteLine(content);

System.Net 中有哪些高级用法?

System.Net 中还有一些高级用法,包括 HttpListener、WebSocket、HttpClient、IPAddress、Dns、NetworkStream 等,这些类和接口可以更加灵活地实现网络通信。

HttpListener:可以实现一个基于 HTTP 协议的服务器,并监听来自客户端的请求。示例代码:

HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
Console.WriteLine("Listening...");
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
string responseString = "<html><body>Hello World!</body></html>";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
listener.Stop();

WebSocket:提供了 WebSocket 协议的客户端和服务器实现,使得 web 应用程序可以轻松地进行双向通信。示例代码:

using System.Net.WebSockets;
using System.Threading.Tasks;

ClientWebSocket webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri("wss://echo.websocket.org/"), CancellationToken.None);
await Task.WhenAll(Receive(webSocket), Send(webSocket));
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);

async Task Receive(ClientWebSocket webSocket)
{
    byte[] buffer = new byte[1024];
    while (webSocket.State == WebSocketState.Open)
    {
        WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, result.Count));
    }
}

async Task Send(ClientWebSocket webSocket)
{
    string message = "Hello World";
    byte[] buffer = Encoding.UTF8.GetBytes(message);
    await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
}

HttpClient:提供了 HTTP 协议的客户端实现,支持 GET、POST 等请求方法。示例代码:

using System.Net.Http.Headers;

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("https://api.example.com/users");
if (response.IsSuccessStatusCode)
{
    string content = await response.Content.ReadAsStringAsync();
    Console.WriteLine(content);
}

IPAddress:表示 IP 地址,可以用于 IP 地址的解析和比较。示例代码:

IPAddress ipAddress1 = IPAddress.Parse("192.168.1.1");
IPAddress ipAddress2 = IPAddress.Parse("192.168.1.100");
Console.WriteLine(ipAddress1 < ipAddress2); // True

Dns:提供了域名系统(DNS)解析功能,可以将域名转换为 IP 地址。示例代码:

IPHostEntry hostEntry = Dns.GetHostEntry("www.example.com");
foreach (var ipAddress in hostEntry.AddressList)
{
    Console.WriteLine(ipAddress.ToString());
}

NetworkStream:表示用于网络通信的数据流,可以用于处理 TCP 或 UDP 连接。示例代码:

TcpClient client = new TcpClient("www.example.com", 80);
NetworkStream stream = client.GetStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write("GET /index.html HTTP/1.1rnHost: www.example.comrnrn");
writer.Flush();
StreamReader reader = new StreamReader(stream);
string response = reader.ReadToEnd();
Console.WriteLine(response);

文章版权声明

 1 原创文章作者:5559,如若转载,请注明出处: https://www.52hwl.com/30963.html

 2 温馨提示:软件侵权请联系469472785#qq.com(三天内删除相关链接)资源失效请留言反馈

 3 下载提示:如遇蓝奏云无法访问,请修改lanzous(把s修改成x)

 免责声明:本站为个人博客,所有软件信息均来自网络 修改版软件,加群广告提示为修改者自留,非本站信息,注意鉴别

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023年7月14日 上午12:00
下一篇 2023年7月15日