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.1\r\nHost: www.example.com\r\n\r\n";
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.1\r\nHost: www.example.com\r\n\r\n";
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 = "Hello World!";
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(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(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.1\r\nHost: www.example.com\r\n\r\n");
writer.Flush();
StreamReader reader = new StreamReader(stream);
string response = reader.ReadToEnd();
Console.WriteLine(response);

当前标题:System.Net基础类库和示例
网页URL:http://www.shufengxianlan.com/qtweb/news41/37791.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联