溫馨提示×

C#使用.NET Framework的網絡功能

c#
小樊
108
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女