在C#中,使用.NET Framework的網(wǎng)絡(luò)功能可以通過多種方式實現(xiàn)
using System;
using System.IO;
using System.Net;
namespace NetworkExample
{
class Program
{
static void Main(string[] args)
{
string url = "https://www.example.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string content = reader.ReadToEnd();
Console.WriteLine("Status Code: " + response.StatusCode);
Console.WriteLine("Content: " + content);
response.Close();
}
}
}
using System;
using System.Net;
namespace NetworkExample
{
class Program
{
static void Main(string[] args)
{
using (WebClient client = new WebClient())
{
string url = "https://www.example.com";
string content = client.DownloadString(url);
Console.WriteLine("Content: " + content);
}
}
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace NetworkExample
{
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
string url = "https://www.example.com";
HttpResponseMessage response = await client.GetAsync(url);
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine("Status Code: " + response.StatusCode);
Console.WriteLine("Content: " + content);
}
}
}
}
TcpClient 和 TcpListener:這兩個類用于創(chuàng)建TCP客戶端和服務(wù)器。
UdpClient:這個類用于創(chuàng)建UDP客戶端和服務(wù)器。
NetworkInformation:這個命名空間包含用于獲取網(wǎng)絡(luò)接口信息、IP地址和其他網(wǎng)絡(luò)相關(guān)信息的類。
這些示例展示了如何使用.NET Framework的網(wǎng)絡(luò)功能。根據(jù)你的需求,你可以選擇適合你的場景的類和方法。