主頁 > .NET開發 > C#語言下使用gRPC、protobuf(Google Protocol Buffers)實作檔案傳輸

C#語言下使用gRPC、protobuf(Google Protocol Buffers)實作檔案傳輸

2020-10-23 15:17:21 .NET開發

  初識gRPC還是一位做JAVA的同事在專案中用到了它,為了C#的客戶端程式和java的服務器程式進行通信和資料交換,當時還是對方編譯成C#,我直接呼叫,

  后來,自己下來做了C#版本gRPC撰寫,搜了很多資料,但許多都是從入門開始?呼叫說“Say Hi!”這種官方標準的入門示例,然后遇到各種問題……

  關于gRPC和Protobuf介紹,就不介紹了,網路上一搜一大把,隨便一抓都是標準的官方,所以直接從使用說起,

  gPRC源代碼:https://github.com/grpc/grpc;

  protobuf的代碼倉庫:github倉庫地址:https://github.com/google/protobuf ;Google下載protobuff下載地址:https://developers.google.com/protocol-buffers/docs/downloads ,

1、新建解決方案

  分別在VS中新建解決方案:GrpcTest;再在解決方案中新建三個專案:GrpcClient、GrpcServer、GrpcService,對應的分別是客戶端(wpf表單程式)、服務端(控制臺程式)、gRPC服務者(控制臺程式),在GrpcClient和GrpcServer專案中添加對GrpcService的參考,

  在VS中對3個專案添加工具包參考:右鍵點擊“解決方案gRPCDemo”,點擊“管理解決方案的NuGet程式包”,在瀏覽中分別搜索"Grpc"、"Grpc.Tools"、"Google.Protobuf",然后點擊右面專案,全選,再點擊安裝(也可以用視圖 -> 視窗 ->  程式包管理器控制臺 中的"Install-Package Grpc"進行這一步,這里不提供這種方法,有興趣自己百度),

2、proto檔案的語法

  對于使用gRPC的通信框架,需要使用到對應的通信檔案,在gRPC中,使用到的是proto格式的檔案,對應的自然有其相應的語法,本文不詳細闡述該檔案的語法,感興趣可以去官網看標準的語法,這兒有一個鏈接,中文翻譯比較全的https://www.codercto.com/a/45372.html,需要對其文章內的1.3進行補充下:

  • required:一個格式良好的訊息一定要含有1個這種欄位,表示該值是必須要設定的,
  • optional:訊息格式中該欄位可以有0個或1個值(不超過1個),
  • repeated:在一個格式良好的訊息中,這種欄位可以重復任意多次(包括0次),重復的值的順序會被保留,表示該值可以重復,相當于java中的List,

  本示例專案實作檔案傳輸,因此在專案GrpcService中添加一個FileTransfer.proto檔案,檔案內容如下:

syntax = "proto3";
package GrpcService;

service FileTransfer{
    rpc FileDownload (FileRequest) returns (stream FileReply);
    rpc FileUpload (stream FileReply) returns(stream FileReturn);
}

//請求下載檔案時,所需下載檔案的檔案名稱集合
message FileRequest{
    repeated string FileNames=1;//檔案名集合
    //repeated重復欄位  類似鏈表;optional可有可無的欄位;required必要設定欄位
    string Mark = 2;//攜帶的包
}

//下載和上傳檔案時的應答資料
message FileReply{
    string FileName=1;//檔案名
    int32 Block = 2;//標記---第幾個資料
    bytes Content = 3;//資料
    string Mark = 4;//攜帶的包
 }

//資料上傳時的回傳值
message FileReturn{
    string FileName=1;//檔案名
    string Mark = 2;//攜帶的包
}

3、編譯proto檔案為C#代碼

  proto檔案僅僅只是定義了相關的資料,如果需要在代碼中使用該格式,就需要將它編譯成C#代碼檔案,

    PS:網上可以找到的編譯,需要下載相關的代碼,見博文,其他的也較為繁瑣,所以按照自己理解的來寫了,注意,我的專案是放在D盤根目錄下的,

  首先打開cmd視窗,然后在視窗中輸入:D:\GrpcTest\packages\Grpc.Tools.2.32.0\tools\windows_x86\protoc.exe -ID:\GrpcTest\GrpcService --csharp_out D:\GrpcTest\GrpcService D:\GrpcTest\GrpcService\FileTransfer.proto --grpc_out D:\GrpcTest\GrpcService --plugin=protoc-gen-grpc=D:\GrpcTest\packages\Grpc.Tools.2.32.0\tools\windows_x86\grpc_csharp_plugin.exe

  輸入上文后,按enter鍵,回車編譯,

  命令解讀:

  • D:\GrpcTest\packages\Grpc.Tools.2.32.0\tools\windows_x86\protoc.exe :呼叫的編譯程式路徑,注意版本不同路徑稍有不一樣,
  • -ID:\GrpcTest\GrpcService :-I 指定一個或者多個目錄,用來搜索.proto檔案的,所以上面那行的D:\GrpcTest\GrpcService\FileTransfer.proto 已經可以換成FileTransfer.proto了,因為-I已經指定了,注意:如果不指定,那就是當前目錄,
  •  --csharp_out D:\GrpcTest\GrpcService D:\GrpcTest\GrpcService\FileTransfer.proto :(--csharp_out)生成C#代碼、存放路徑、檔案,當然還能cpp_out、java_out、javanano_out、js_out、objc_out、php_out、python_out、ruby_out 這時候你就應該知道,可以支持多語言的,才用的,生成一些檔案,然后給各個語言平臺呼叫,引數1(D:\GrpcTest\GrpcService)是輸出路徑,引數2(D:\GrpcTest\GrpcService\FileTransfer.proto)是proto的檔案名或者路徑,
  •  --grpc_out D:\GrpcTest\GrpcService :grpc_out是跟服務相關,創建,呼叫,系結,實作相關,生成的玩意叫xxxGrpc.cs,與前面的區別是csharp_out是輸出類似于咱們平時寫的物體類,介面,定義之類的,生成的檔案叫xxx.cs
  • --plugin=protoc-gen-grpc=D:\GrpcTest\packages\Grpc.Tools.2.32.0\tools\windows_x86\grpc_csharp_plugin.exe :這個就是csharp的插件,python有python的,java有java的,

  編譯后,會在新增兩個檔案(檔案位置與你的輸出位置有關),并將兩個檔案加入到GrpcService專案中去:

    

 

 4、撰寫服務端的檔案傳輸服務

  在GrpcServer專案中,新建一個FileImpl并繼承自GrpcService.FileTransfer.FileTransferBase,然后復寫其方法FileDownload和FileUpload方法,以供客戶端進行呼叫,

/// <summary>
/// 檔案傳輸類
/// </summary>
class FileImpl:GrpcService.FileTransfer.FileTransferBase
{
    /// <summary>
    /// 檔案下載
    /// </summary>
    /// <param name="request">下載請求</param>
    /// <param name="responseStream">檔案寫入流</param>
    /// <param name="context">站點背景關系</param>
    /// <returns></returns>
    public override async Task FileDownload(FileRequest request, global::Grpc.Core.IServerStreamWriter<FileReply> responseStream, global::Grpc.Core.ServerCallContext context)
    {
        List<string> lstSuccFiles = new List<string>();//傳輸成功的檔案
        DateTime startTime = DateTime.Now;//傳輸檔案的起始時間
        int chunkSize = 1024 * 1024;//每次讀取的資料
        var buffer = new byte[chunkSize];//資料緩沖區
        FileStream fs = null;//檔案流
        try
        {
            //reply.Block數字的含義是服務器和客戶端約定的
            for (int i = 0; i < request.FileNames.Count; i++)
            {
                string fileName = request.FileNames[i];//檔案名
                string filePath = Path.GetFullPath($".//Files\\{fileName}");//檔案路徑
                FileReply reply = new FileReply
                {
                    FileName = fileName,
                    Mark = request.Mark
                };//應答資料
                Console.WriteLine($"{request.Mark},下載檔案:{filePath}");//寫入日志,下載檔案
                if (File.Exists(filePath))
                {
                    fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, chunkSize, useAsync: true);

                    //fs.Length  可以告訴客戶端所傳檔案大小
                    int readTimes = 0;//讀取次數
                    while (true)
                    {
                        int readSise = fs.Read(buffer, 0, buffer.Length);//讀取資料
                        if (readSise > 0)//讀取到了資料,有資料需要發送
                        {
                            reply.Block = ++readTimes;
                            reply.Content = Google.Protobuf.ByteString.CopyFrom(buffer, 0, readSise);
                            await responseStream.WriteAsync(reply);
                        }
                        else//沒有資料了,就告訴對方,讀取完了
                        {
                            reply.Block = 0;
                            reply.Content = Google.Protobuf.ByteString.Empty;
                            await responseStream.WriteAsync(reply);
                            lstSuccFiles.Add(fileName);
                            Console.WriteLine($"{request.Mark},完成發送檔案:{filePath}");//日志,記錄發送成功
                            break;//跳出去
                        }
                    }
                    fs?.Close();
                }
                else
                {
                    Console.WriteLine($"檔案【{filePath}】不存在,");//寫入日志,檔案不存在
                    reply.Block = -1;//-1的標記為檔案不存在
                    await responseStream.WriteAsync(reply);//告訴客戶端,檔案狀態
                }
            }
            //告訴客戶端,檔案傳輸完成
            await responseStream.WriteAsync(new FileReply
            {
                FileName = string.Empty,
                Block = -2,//告訴客戶端,檔案已經傳輸完成
                Content = Google.Protobuf.ByteString.Empty,
                Mark = request.Mark
            });
        }
        catch(Exception ex)
        {
            Console.WriteLine($"{request.Mark},發生例外({ex.GetType()}):{ex.Message}");
        }
        finally
        {
            fs?.Dispose();
        }
        Console.WriteLine($"{request.Mark},檔案傳輸完成,共計【{lstSuccFiles.Count / request.FileNames.Count}】,耗時:{DateTime.Now - startTime}");
    }


    /// <summary>
    /// 上傳檔案
    /// </summary>
    /// <param name="requestStream">請求流</param>
    /// <param name="responseStream">回應流</param>
    /// <param name="context">站點背景關系</param>
    /// <returns></returns>
    public override async Task FileUpload(global::Grpc.Core.IAsyncStreamReader<FileReply> requestStream, global::Grpc.Core.IServerStreamWriter<FileReturn> responseStream, global::Grpc.Core.ServerCallContext context)
    {
        List<string> lstFilesName = new List<string>();//檔案名
        List<FileReply> lstContents = new List<FileReply>();//資料集合

        FileStream fs = null;
        DateTime startTime = DateTime.Now;//開始時間
        string mark = string.Empty;
        string savePath = string.Empty;
        try
        {
            //reply.Block數字的含義是服務器和客戶端約定的
            while (await requestStream.MoveNext())//讀取資料
            {
                var reply = requestStream.Current;
                mark = reply.Mark;
                if (reply.Block == -2)//傳輸完成
                {
                    Console.WriteLine($"{mark},完成上傳檔案,共計【{lstFilesName.Count}】個,耗時:{DateTime.Now-startTime}");
                    break;
                }
                else if (reply.Block == -1)//取消了傳輸
                {
                    Console.WriteLine($"檔案【{reply.FileName}】取消傳輸!");//寫入日志
                    lstContents.Clear();
                    fs?.Close();//釋放檔案流
                    if (!string.IsNullOrEmpty(savePath) && File.Exists(savePath))//如果傳輸不成功,洗掉該檔案
                    {
                        File.Delete(savePath);
                    }
                    savePath = string.Empty;
                    break;
                }
                else if(reply.Block==0)//檔案傳輸完成
                {
                    if (lstContents.Any())//如果還有資料,就寫入檔案
                    {
                        lstContents.OrderBy(c => c.Block).ToList().ForEach(c => c.Content.WriteTo(fs));
                        lstContents.Clear();
                    }
                    lstFilesName.Add(savePath);//傳輸成功的檔案
                    fs?.Close();//釋放檔案流
                    savePath = string.Empty;

                    //告知客戶端,已經完成傳輸
                    await responseStream.WriteAsync(new FileReturn
                    {
                        FileName= reply.FileName,
                        Mark=mark
                    });
                }
                else
                {
                    if(string.IsNullOrEmpty(savePath))//有新檔案來了
                    {
                        savePath = Path.GetFullPath($".//Files\\{reply.FileName}");//檔案路徑
                        fs = new FileStream(savePath, FileMode.Create, FileAccess.ReadWrite);
                        Console.WriteLine($"{mark},上傳檔案:{savePath},{DateTime.UtcNow.ToString("HH:mm:ss:ffff")}");
                    }
                    lstContents.Add(reply);//加入鏈表
                    if (lstContents.Count() >= 20)//每個包1M,20M為一個集合,一起寫入資料,
                    {
                        lstContents.OrderBy(c => c.Block).ToList().ForEach(c => c.Content.WriteTo(fs));
                        lstContents.Clear();
                    }
                }
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine($"{mark},發生例外({ex.GetType()}):{ex.Message}");
        }
        finally
        {
            fs?.Dispose();
        }
    }
}
View Code

  在main函式中添加服務:

class Program
{
    static void Main(string[] args)
    {
        //提供服務
        Server server = new Server()
        {
            Services = {GrpcService.FileTransfer.BindService(new FileImpl())},
            Ports = {new ServerPort("127.0.0.1",50000,ServerCredentials.Insecure)}
        };
        //服務開始
        server.Start();

        while(Console.ReadLine().Trim().ToLower()!="exit")
        {

        }
        //結束服務
        server.ShutdownAsync();
    }
}

5、撰寫客戶端的檔案傳輸功能

  首先定義一個檔案傳輸結果類TransferResult<T>,用于存放檔案的傳輸結果,

/// <summary>
/// 傳輸結果
/// </summary>
/// <typeparam name="T"></typeparam>
class TransferResult<T>
{
    /// <summary>
    /// 傳輸是否成功
    /// </summary>
    public bool IsSuccessful { get; set; }
    /// <summary>
    /// 訊息
    /// </summary>
    public string Message { get; set; }

    /// <summary>
    /// 標記型別
    /// </summary>
    public T Tag { get; set; } = default;
}

  然后在GrpcClinet專案中添加一個FileTransfer的類,并實作相關方法:

class FileTransfer
{

    /// <summary>
    /// 獲取通信客戶端
    /// </summary>
    /// <returns>通信頻道、客戶端</returns>
    static (Channel, GrpcService.FileTransfer.FileTransferClient) GetClient()
    {
        //偵聽IP和埠要和服務器一致
        Channel channel = new Channel("127.0.0.1", 50000, ChannelCredentials.Insecure);
        var client = new GrpcService.FileTransfer.FileTransferClient(channel);
        return (channel, client);
    }

    /// <summary>
    /// 下載檔案
    /// </summary>
    /// <param name="fileNames">需要下載的檔案集合</param>
    /// <param name="mark">標記</param>
    /// <param name="saveDirectoryPath">保存路徑</param>
    /// <param name="cancellationToken">異步取消命令</param>
    /// <returns>下載任務(是否成功、原因、失敗檔案名)</returns>
    public static async Task<TransferResult<List<string>>> FileDownload(List<string> fileNames, string mark, string saveDirectoryPath, System.Threading.CancellationToken cancellationToken = new System.Threading.CancellationToken())
    {
        var result = new TransferResult<List<string>>() { Message = $"檔案保存路徑不正確:{saveDirectoryPath}" };
        if (!System.IO.Directory.Exists(saveDirectoryPath))
        {
            return await Task.Run(() => result);//檔案路徑不存在
        }
        if (fileNames.Count == 0)
        {
            result.Message = "未包含任何檔案";
            return await Task.Run(() => result);//檔案路徑不存在
        }
        result.Message = "未能連接到服務器";
        FileRequest request = new FileRequest() { Mark = mark };//請求資料
        request.FileNames.AddRange(fileNames);//將需要下載的檔案名賦值
        var lstSuccFiles = new List<string>();//傳輸成功的檔案
        string savePath = string.Empty;//保存路徑
        System.IO.FileStream fs = null;
        Channel channel = null;//申明通信頻道
        GrpcService.FileTransfer.FileTransferClient client = null;
        DateTime startTime = DateTime.Now;
        try
        {
            (channel, client) = GetClient();
            using (var call = client.FileDownload(request))
            {
                List<FileReply> lstContents = new List<FileReply>();//存放接收的資料
                var reaponseStream = call.ResponseStream;
                //reaponseStream.Current.Block數字的含義是服務器和客戶端約定的
                while (await reaponseStream.MoveNext(cancellationToken))//開始接收資料
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }
                    if (reaponseStream.Current.Block == -2)//說明檔案已經傳輸完成了
                    {
                        result.Message = $"完成下載任務【{lstSuccFiles.Count}/{fileNames.Count}】,耗時:{DateTime.Now - startTime}";
                        result.IsSuccessful = true;
                        break;
                    }
                    else if (reaponseStream.Current.Block == -1)//當前檔案傳輸錯誤
                    {
                        Console.WriteLine($"檔案【{reaponseStream.Current.FileName}】傳輸失敗!");//寫入日志
                        lstContents.Clear();
                        fs?.Close();//釋放檔案流
                        if (!string.IsNullOrEmpty(savePath) && File.Exists(savePath))//如果傳輸不成功,洗掉該檔案
                        {
                            File.Delete(savePath);
                        }
                        savePath = string.Empty;
                    }
                    else if (reaponseStream.Current.Block == 0)//當前檔案傳輸完成
                    {
                        if (lstContents.Any())//如果還有資料,就寫入檔案
                        {
                            lstContents.OrderBy(c => c.Block).ToList().ForEach(c => c.Content.WriteTo(fs));
                            lstContents.Clear();
                        }
                        lstSuccFiles.Add(reaponseStream.Current.FileName);//傳輸成功的檔案
                        fs?.Close();//釋放檔案流
                        savePath = string.Empty;
                    }
                    else//有檔案資料過來
                    {
                        if (string.IsNullOrEmpty(savePath))//如果位元組流為空,則說明時新的檔案資料來了
                        {
                            savePath = Path.Combine(saveDirectoryPath, reaponseStream.Current.FileName);
                            fs = new FileStream(savePath, FileMode.Create, FileAccess.ReadWrite);
                        }
                        lstContents.Add(reaponseStream.Current);//加入鏈表
                        if (lstContents.Count() >= 20)//每個包1M,20M為一個集合,一起寫入資料,
                        {
                            lstContents.OrderBy(c => c.Block).ToList().ForEach(c => c.Content.WriteTo(fs));
                            lstContents.Clear();
                        }
                    }
                }
            }
            fs?.Close();//釋放檔案流
            if (!result.IsSuccessful &&!string.IsNullOrEmpty(savePath)&& File.Exists(savePath))//如果傳輸不成功,那么久洗掉該檔案
            {
                File.Delete(savePath);
            }
        }
        catch (Exception ex)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                fs?.Close();//釋放檔案流
                result.IsSuccessful = false;
                result.Message = $"用戶取消下載,已完成下載【{lstSuccFiles.Count}/{fileNames.Count}】,耗時:{DateTime.Now - startTime}";
            }
            else
            {
                result.Message = $"檔案傳輸發生例外:{ex.Message}";
            }
        }
        finally
        {
            fs?.Dispose();
        }
        result.Tag = fileNames.Except(lstSuccFiles).ToList();//獲取失敗檔案集合
        //關閉通信、并回傳結果
        return await channel?.ShutdownAsync().ContinueWith(t => result);
    }


    /// <summary>
    /// 檔案上傳
    /// </summary>
    /// <param name="filesPath">檔案路徑</param>
    /// <param name="mark">標記</param>
    /// <param name="cancellationToken">異步取消命令</param>
    /// <returns>下載任務(是否成功、原因、成功的檔案名)</returns>
    public static async Task<TransferResult<List<string>>> FileUpload(List<string> filesPath, string mark, System.Threading.CancellationToken cancellationToken=new System.Threading.CancellationToken())
    {
        var result = new TransferResult<List<string>> { Message = "沒有檔案需要下載" };
        if (filesPath.Count == 0)
        {
            return await Task.Run(() => result);//沒有檔案需要下載
        }
        result.Message = "未能連接到服務器,";
        var lstSuccFiles = new List<string>();//傳輸成功的檔案
        int chunkSize = 1024 * 1024;
        byte[] buffer = new byte[chunkSize];//每次發送的大小
        FileStream fs = null;//檔案流
        Channel channel = null;//申明通信頻道
        GrpcService.FileTransfer.FileTransferClient client = null;
        DateTime startTime = DateTime.Now;
        try
        {
            (channel, client) = GetClient();
            using(var stream=client.FileUpload())//連接上傳檔案的客戶端
            {
                //reply.Block數字的含義是服務器和客戶端約定的
                foreach (var filePath in filesPath)//遍歷集合
                {
                    if(cancellationToken.IsCancellationRequested)
                        break;//取消了傳輸
                    FileReply reply = new FileReply()
                    {
                        FileName=Path.GetFileName(filePath),
                        Mark=mark
                    };
                    if(!File.Exists(filePath))//檔案不存在,繼續下一輪的發送
                    {
                        Console.WriteLine($"檔案不存在:{filePath}");//寫入日志
                        continue;
                    }
                    fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, chunkSize, useAsync: true);
                    int readTimes = 0;
                    while(true)
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            reply.Block = -1;//取消了傳輸
                            reply.Content = Google.Protobuf.ByteString.Empty;
                            await stream.RequestStream.WriteAsync(reply);//發送取消傳輸的命令
                            break;//取消了傳輸
                        }
                        int readSize = fs.Read(buffer, 0, buffer.Length);//讀取資料
                        if(readSize>0)
                        {
                            reply.Block = ++readTimes;//更新標記,發送資料
                            reply.Content = Google.Protobuf.ByteString.CopyFrom(buffer, 0, readSize);
                            await stream.RequestStream.WriteAsync(reply);
                        }
                        else
                        {
                            Console.WriteLine($"完成檔案【{filePath}】的上傳,");
                            reply.Block = 0;//傳送本次檔案發送結束的標記
                            reply.Content = Google.Protobuf.ByteString.Empty;
                            await stream.RequestStream.WriteAsync(reply);//發送結束標記
                            //等待服務器回傳
                            await stream.ResponseStream.MoveNext(cancellationToken);
                            if(stream.ResponseStream.Current!=null&&stream.ResponseStream.Current.Mark==mark)
                            {
                                lstSuccFiles.Add(filePath);//記錄成功的檔案
                            }
                            break;//發送下一個檔案
                        }
                    }
                    fs?.Close();
                }
                if (!cancellationToken.IsCancellationRequested)
                {
                    result.IsSuccessful = true;
                    result.Message = $"完成檔案上傳,共計【{lstSuccFiles.Count}/{filesPath.Count}】,耗時:{DateTime.Now - startTime}";

                    await stream.RequestStream.WriteAsync(new FileReply
                    {
                        Block = -2,//傳輸結束
                        Mark = mark
                    }) ;//發送結束標記
                }
            }
        }
        catch(Exception ex)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                fs?.Close();//釋放檔案流
                result.IsSuccessful = false;
                result.Message = $"用戶取消了上傳檔案,已完成【{lstSuccFiles.Count}/{filesPath.Count}】,耗時:{DateTime.Now - startTime}";
            }
            else
            {
                result.Message = $"檔案上傳發生例外({ex.GetType()}):{ex.Message}";
            }
        }
        finally
        {
            fs?.Dispose();
        }
        Console.WriteLine(result.Message);
        result.Tag = lstSuccFiles;
        //關閉通信、并回傳結果
        return await channel?.ShutdownAsync().ContinueWith(t => result);
    }
}
View Code

  現在可以在客戶端表單內進行呼叫了:

private string GetFilePath()
{
    // Create OpenFileDialog 
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

    // Set filter for file extension and default file extension 
    dlg.Title = "選擇檔案";
    dlg.Filter = "所有檔案(*.*)|*.*";
    dlg.FileName = "選擇檔案夾.";
    dlg.FilterIndex = 1;
    dlg.ValidateNames = false;
    dlg.CheckFileExists = false;
    dlg.CheckPathExists = true;
    dlg.Multiselect = false;//允許同時選擇多個檔案 

    // Display OpenFileDialog by calling ShowDialog method 
    Nullable<bool> result = dlg.ShowDialog();

    // Get the selected file name and display in a TextBox 
    if (result == true)
    {
        // Open document 
        return dlg.FileName;
    }

    return string.Empty;
}
// 打開檔案
private void btnOpenUpload_Click(object sender, RoutedEventArgs e)
{
    lblUploadPath.Content = GetFilePath();
}
CancellationTokenSource uploadTokenSource;
//上傳
private async void btnUpload_Click(object sender, RoutedEventArgs e)
{
    lblMessage.Content = string.Empty;

    uploadTokenSource = new CancellationTokenSource();
    List<string> fileNames = new List<string>();
    fileNames.Add(lblUploadPath.Content.ToString());
    var result = await ServerNet.FileTransfer.FileUpload(fileNames, "123", uploadTokenSource.Token);

    lblMessage.Content = result.Message;

    uploadTokenSource = null;
}
//取消上傳
private void btnCancelUpload_Click(object sender, RoutedEventArgs e)
{
    uploadTokenSource?.Cancel();
}


//打開需要下載的檔案
private void btnOpenDownload_Click(object sender, RoutedEventArgs e)
{
    txtDownloadPath.Text = GetFilePath();
}
//下載檔案
private async void btnDownload_Click(object sender, RoutedEventArgs e)
{
    lblMessage.Content = string.Empty;

    downloadTokenSource = new CancellationTokenSource();
    List<string> fileNames = new List<string>();
    fileNames.Add(System.IO.Path.GetFileName(txtDownloadPath.Text));
    var result=  await ServerNet.FileTransfer.FileDownload(fileNames, "123", Environment.CurrentDirectory, downloadTokenSource.Token);

    lblMessage.Content = result.Message;

    downloadTokenSource = null;
}
CancellationTokenSource   downloadTokenSource;
//下載取消
private void btnCancelDownload_Click(object sender, RoutedEventArgs e)
{
    downloadTokenSource?.Cancel();
}

6、源代碼

  https://files.cnblogs.com/files/pilgrim/GrpcTest.rar

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/187314.html

標籤:.NET技术

上一篇:推薦一套完整的后臺管理系統(附原始碼),非常實用,賺錢就靠它了!

下一篇:.Net Core實作基于Quart.Net的任務管理

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more