首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> C# 入門

C# 網路程式設計概論(三):同步 Socket 網頁下載器完整實作

     編輯:C# 入門

完整實作:網頁下載器

結合前兩節知識,實作一個以 TCP 連線下載網頁預設頁面並存檔的 Windows Forms 應用程式。

執行畫面

網頁下載器執行畫面

核心程式碼:DoSocketGet 方法

private string DoSocketGet(string server)
{
    Encoding ASCII = Encoding.ASCII;
    // HTTP GET 請求
    string Get = "GET / HTTP/1.1 Host: " + server + " Connection: Close ";
    Byte[] ByteGet = ASCII.GetBytes(Get);
    Byte[] RecvBytes = new Byte[256];
    String strRetPage = null;

    try
    {
        // 解析伺服器 IP 並建立端點
        IPAddress hostadd = Dns.Resolve(server).AddressList[0];
        IPEndPoint EPhost = new IPEndPoint(hostadd, 80);

        // 建立 TCP Socket
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        // 連線
        s.Connect(EPhost);
    }
    catch (Exception se)
    {
        MessageBox.Show("連線錯誤:" + se.Message, "提示", MessageBoxButtons.RetryCancel, MessageBoxIcon.Information);
    }

    if (!s.Connected)
    {
        strRetPage = "無法連線至伺服器!";
        return strRetPage;
    }

    try
    {
        // 發送 HTTP GET
        s.Send(ByteGet, ByteGet.Length, SocketFlags.None);
    }
    catch (Exception ce)
    {
        MessageBox.Show("發送錯誤:" + ce.Message, "提示", MessageBoxButtons.RetryCancel, MessageBoxIcon.Information);
    }

    // 接收回應
    Int32 bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
    strRetPage = "以下是伺服器 " + server + " 上的預設網頁: ";
    strRetPage += ASCII.GetString(RecvBytes, 0, bytes);

    while (bytes > 0)
    {
        bytes = s.Receive(RecvBytes, RecvBytes.Length, SocketFlags.None);
        strRetPage += ASCII.GetString(RecvBytes, 0, bytes);
    }

    // 關閉連線
    s.Shutdown(SocketShutdown.Both);
    s.Close();

    return strRetPage;
}

下載按鈕事件

private void Download_Click(object sender, System.EventArgs e)
{
    byte[] content = Encoding.ASCII.GetBytes(DoSocketGet(ServerAddress.Text));
    try
    {
        // 寫入檔案(程式碼截斷,完整版應包含 FileStream 寫入)
        FileStream fs = new FileStream(Filename.Text, FileMode.Create);
        fs.Write(content, 0, content.Length);
        fs.Close();
        MessageBox.Show("下載完成!");
    }
    catch (Exception ex)
    {
        MessageBox.Show("檔案寫入錯誤:" + ex.Message);
    }
}

關鍵技術點總結

  1. DNS 解析:Dns.Resolve 取得 IPAddress
  2. 端點建立:IPEndPoint 組合 IP + Port 80
  3. TCP Socket:Stream 類型 + Tcp 協定
  4. HTTP 協定:手工組裝 GET / HTTP/1.1 請求
  5. 迴圈接收:直到 Receive 回傳 0 位元組
  6. 資源管理:Shutdown + Close 確保資料完整
  7. 檔案儲存:FileStream 寫入位元組陣列

擴充建議

  • 支援 HTTPS(需 SslStream)
  • 解析 HTTP 回應標頭與內容分離
  • 加入非同步模式避免 UI 凍結
  • 支援 Proxy、Cookie、重導向處理
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved