c#

C#使用.NET Framework的网络功能

小樊
81
2024-09-16 09:05:25
栏目: 编程语言

在C#中,使用.NET Framework的网络功能可以通过多种方式实现

  1. HttpWebRequest 和 HttpWebResponse:这两个类用于发送HTTP请求并接收HTTP响应。
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();
        }
    }
}
  1. WebClient:这是一个简化的类,用于发送HTTP请求并接收HTTP响应。
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);
            }
        }
    }
}
  1. HttpClient:这是一个更高级的类,用于发送HTTP请求并接收HTTP响应。它提供了异步操作和更好的性能。
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);
            }
        }
    }
}
  1. TcpClient 和 TcpListener:这两个类用于创建TCP客户端和服务器。

  2. UdpClient:这个类用于创建UDP客户端和服务器。

  3. NetworkInformation:这个命名空间包含用于获取网络接口信息、IP地址和其他网络相关信息的类。

这些示例展示了如何使用.NET Framework的网络功能。根据你的需求,你可以选择适合你的场景的类和方法。

0
看了该问题的人还看了