首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 網路程式設計:協議與檔案傳輸 (6) — 客戶端檔案傳送實作與 SendStatus 進度類別

     編輯:關於C語言

程式碼重點說明

  1. 圖片路徑:Main() 中指定應用程式目錄下的 Client01.jpg、Client02.jpg、Client03.jpg(偵錯模式置於 Bin\Debug)。
  2. 同步/非同步並存:提供 SendFile()(同步)、BeginSendFile()(非同步)、私有 SendFile() 輔助。實務上檔案傳輸幾乎必須用非同步。
  3. 鎖的必要性:SendMessage() 對 streamToServer 加鎖,因 SendFile() 為多執行緒存取且會呼叫 SendMessage()。
  4. 職責分離:SendStatus 獨立記錄/顯示傳送狀態(已送位元組、百分比),原本寫在 Client 內,後發現不屬於 Client 核心職責,遂獨立成類——「當方法與類別名稱不符時,該建立新類別」。

SendStatus 類別完整程式碼

// 即時計算檔案傳送狀態
public class SendStatus {
    private FileInfo info;
    private long fileBytes;

    public SendStatus(string filePath) {
        info = new FileInfo(filePath);
        fileBytes = info.Length;
    }

    public void PrintStatus(int sent) {
        string percent = GetPercent(sent);
        Console.WriteLine("Sending {0} bytes, {1}% ...", sent, percent);
    }

    // 取得傳送百分比(保留一位小數)
    public string GetPercent(int sent) {
        decimal allBytes = Convert.ToDecimal(fileBytes);
        decimal currentSent = Convert.ToDecimal(sent);
        decimal percent = (currentSent / allBytes) * 100;
        percent = Math.Round(percent, 1);
        return (percent.ToString() == "100.0") ? "100" : percent.ToString();
    }
}

程式測試:伺服器端輸出

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved