在C#中,使用.NET Framework的网络功能可以通过多种方式实现
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:这两个类用于创建TCP客户端和服务器。
UdpClient:这个类用于创建UDP客户端和服务器。
NetworkInformation:这个命名空间包含用于获取网络接口信息、IP地址和其他网络相关信息的类。
这些示例展示了如何使用.NET Framework的网络功能。根据你的需求,你可以选择适合你的场景的类和方法。