Blazor(WebAssembly) + .NETCore 實現鬥地主

来源:https://www.cnblogs.com/nasha/archive/2019/12/15/12040520.html
-Advertisement-
Play Games

之前群里大神發了一個 html5+ .NETCore的鬥地主,剛好在看Blazor WebAssembly 就嘗試重寫試試。 還有就是有些標題黨了,因為文章里幾乎沒有鬥地主的相關實現:),這裡主要介紹一些Blazor前端的一些方法實現而鬥地主的實現總結來說就是獲取數據綁定UI,語法上基本就是Razo ...


  之前群里大神發了一個 html5+ .NETCore的鬥地主,剛好在看Blazor WebAssembly 就嘗試重寫試試。

  還有就是有些標題黨了,因為文章里幾乎沒有鬥地主的相關實現:),這裡主要介紹一些Blazor前端的一些方法實現而鬥地主的實現總結來說就是獲取數據綁定UI,語法上基本就是Razor,頁面上的註入語法等不在重覆介紹,完整實現可以查看github:https://github.com/saber-wang/FightLandlord/tree/master/src/BetGame.DDZ.WasmClient,線上演示:http://39.106.159.180:31000/

  另外強調一下Blazor WebAssembly 是純前端框架,所有相關組件等都會下載到瀏覽器運行,要和MVC、Razor Pages等區分開來

  當前是基於NetCore3.1和Blazor WebAssembly 3.1.0-preview4。

  Blazor WebAssembly預設是沒有安裝的,在命令行執行下邊的命令安裝Blazor WebAssembly模板。

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.1.0-preview4.19579.2

  

  選擇Blazor應用,跟著往下就會看到Blazor WebAssembly App模板,如果看不到就在ASP.NET Core3.0和3.1之間切換一下。

  

  新建後項目結構如下。

  

  一眼看過去,大體和Razor Pages 差不多。Program.cs也和ASP.NET Core差不多,區別是返回了一個IWebAssemblyHostBuilder。

  

 public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

public static IWebAssemblyHostBuilder CreateHostBuilder(string[] args) =>
            BlazorWebAssemblyHost.CreateDefaultBuilder()
                .UseBlazorStartup<Startup>();

  Startup.cs結構也和ASP.NET Core基本一致。Configure中接受的是IComponentsApplicationBuilder,並指定了啟動組件

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            //web api 請求
            services.AddScoped<ApiService>();
            //Js Function調用
            services.AddScoped<FunctionHelper>();
            //LocalStorage存儲
            services.AddScoped<LocalStorage>();
            //AuthenticationStateProvider實現
            services.AddScoped<CustomAuthStateProvider>();
            services.AddScoped<AuthenticationStateProvider>(s => s.GetRequiredService<CustomAuthStateProvider>());
            //啟用認證
            services.AddAuthorizationCore();
        }

        public void Configure(IComponentsApplicationBuilder app)
        {
            WebAssemblyHttpMessageHandlerOptions.DefaultCredentials = FetchCredentialsOption.Include;

            app.AddComponent<App>("app");
        }
    }

 

  Blazor WebAssembly 中也支持DI,註入方式與生命周期與ASP.NET Core一致,但是Scope生命周期不太一樣,註冊的服務的行為類似於 Singleton 服務。

  預設已註入了HttpClientIJSRuntimeNavigationManager,具體可以看官方文檔介紹。

  App.razor中定義了路由和預設路由,修改添加AuthorizeRouteView和CascadingAuthenticationState以AuthorizeView、AuthenticationState級聯參數用於認證和當前的身份驗證狀態。

  

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
    </Found>
    <NotFound>
        <CascadingAuthenticationState>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </CascadingAuthenticationState>
    </NotFound>
</Router>

  自定義AuthenticationStateProvider並註入為AuthorizeView和CascadingAuthenticationState組件提供認證。

            //AuthenticationStateProvider實現
            services.AddScoped<CustomAuthStateProvider>();
            services.AddScoped<AuthenticationStateProvider>(s => s.GetRequiredService<CustomAuthStateProvider>());

 

public class CustomAuthStateProvider : AuthenticationStateProvider
    {
        ApiService _apiService;
        Player _playerCache;
        public CustomAuthStateProvider(ApiService apiService)
        {
            _apiService = apiService;
        }

        public override async Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            var player = _playerCache??= await _apiService.GetPlayer();

            if (player == null)
            {
                return new AuthenticationState(new ClaimsPrincipal());
            }
            else
            {
                //認證通過則提供ClaimsPrincipal
                var user = Utils.GetClaimsIdentity(player);
                return new AuthenticationState(user);
            }

        }
        /// <summary>
        /// 通知AuthorizeView等用戶狀態更改
        /// </summary>
        public void NotifyAuthenticationState()
        {
            NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
        }
        /// <summary>
        /// 提供Player並通知AuthorizeView等用戶狀態更改
        /// </summary>
        public void NotifyAuthenticationState(Player player)
        {
            _playerCache = player;
            NotifyAuthenticationState();
        }
    }

  我們這個時候就可以在組件上添加AuthorizeView根據用戶是否有權查看來選擇性地顯示 UI,該組件公開了一個 AuthenticationState 類型的 context 變數,可以使用該變數來訪問有關已登錄用戶的信息。

  

<AuthorizeView>
    <Authorized>
     //認證通過 @context.User
    </Authorized>
    <NotAuthorized>
     //認證不通過
    </NotAuthorized>
</AuthorizeView>

   使身份驗證狀態作為級聯參數

[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }

  獲取當前用戶信息

    private async Task GetPlayer()
    {
        var user = await authenticationStateTask;
        if (user?.User?.Identity?.IsAuthenticated == true)
        {
            player = new Player
            {
                Balance = Convert.ToInt32(user.User.FindFirst(nameof(Player.Balance)).Value),
                GameState = user.User.FindFirst(nameof(Player.GameState)).Value,
                Id = user.User.FindFirst(nameof(Player.Id)).Value,
                IsOnline = Convert.ToBoolean(user.User.FindFirst(nameof(Player.IsOnline)).Value),
                Nick = user.User.FindFirst(nameof(Player.Nick)).Value,
                Score = Convert.ToInt32(user.User.FindFirst(nameof(Player.Score)).Value),
            };
            await ConnectWebsocket();
        }
    }

  註冊用戶並通知AuthorizeView狀態更新

    private async Task GetOrAddPlayer(MouseEventArgs e)
    {
        GetOrAddPlayering = true;
        player = await ApiService.GetOrAddPlayer(editNick);
        this.GetOrAddPlayering = false;

        if (player != null)
        {
            CustomAuthStateProvider.NotifyAuthenticationState(player);
            await ConnectWebsocket();
        }

    }

 

  JavaScript 互操作,雖然很希望完全不操作JavaScript,但目前版本的Web WebAssembly不太現實,例如彈窗、WebSocket、本地存儲等,Blazor中操作JavaScript主要靠IJSRuntime 抽象。

  從Blazor操作JavaScript比較簡單,操作的JavaScript需要是公開的,這裡實現從Blazor調用alert和localStorage如下

  

public class FunctionHelper
    {
        private readonly IJSRuntime _jsRuntime;

        public FunctionHelper(IJSRuntime jsRuntime)
        {
            _jsRuntime = jsRuntime;
        }

        public ValueTask Alert(object message)
        {
            //無返回值使用InvokeVoidAsync
            return _jsRuntime.InvokeVoidAsync("alert", message);
        }
    }
public class LocalStorage
    {
        private readonly IJSRuntime _jsRuntime;
        private readonly static JsonSerializerOptions SerializerOptions = new JsonSerializerOptions();

        public LocalStorage(IJSRuntime jsRuntime)
        {
            _jsRuntime = jsRuntime;
        }
        public ValueTask SetAsync(string key, object value)
        {

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Cannot be null or empty", nameof(key));
            }

            var json = JsonSerializer.Serialize(value, options: SerializerOptions);

            return _jsRuntime.InvokeVoidAsync("localStorage.setItem", key, json);
        }
        public async ValueTask<T> GetAsync<T>(string key)
        {

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Cannot be null or empty", nameof(key));
            }

            //有返回值使用InvokeAsync
            var json =await _jsRuntime.InvokeAsync<string>("localStorage.getItem", key);
            if (json == null)
            {
                return default;
            }

            return JsonSerializer.Deserialize<T>(json, options: SerializerOptions);
        }
        public ValueTask DeleteAsync(string key)
        {
            return _jsRuntime.InvokeVoidAsync(
                $"localStorage.removeItem",key);
        }
    }

  從JavaScript調用C#方法則需要把C#方法使用[JSInvokable]特性標記且必須為公開的。調用C#靜態方法看這裡,這裡主要介紹調用C#的實例方法。

  因為Blazor Wasm暫時不支持ClientWebSocket,所以我們用JavaScript互操作來實現WebSocket的鏈接與C#方法的回調。

  使用C#實現一個調用JavaScript的WebSocket,並使用DotNetObjectReference.Create包裝一個實例傳遞給JavaScript方法的參數(dotnetHelper),這裡直接傳遞了當前實例。

    [JSInvokable]
    public async Task ConnectWebsocket()
    {
        Console.WriteLine("ConnectWebsocket");
        var serviceurl = await ApiService.ConnectWebsocket();
        //TODO ConnectWebsocket
        if (!string.IsNullOrWhiteSpace(serviceurl))
            await _jsRuntime.InvokeAsync<string>("newWebSocket", serviceurl, DotNetObjectReference.Create(this));
    }

  JavaScript代碼里使用參數(dotnetHelper)接收的實例調用C#方法(dotnetHelper.invokeMethodAsync('方法名',方法參數...))。

 

var gsocket = null;
var gsocketTimeId = null;
function newWebSocket(url, dotnetHelper)
{
    console.log('newWebSocket');
    if (gsocket) gsocket.close();
    gsocket = null;
    gsocket = new WebSocket(url);
    gsocket.onopen = function (e) {
        console.log('websocket connect');
        //調用C#的onopen();
        dotnetHelper.invokeMethodAsync('onopen')
    };
    gsocket.onclose = function (e) {
        console.log('websocket disconnect');
        dotnetHelper.invokeMethodAsync('onclose')
        gsocket = null;
        clearTimeout(gsocketTimeId);
        gsocketTimeId = setTimeout(function () {
            console.log('websocket onclose ConnectWebsocket');
            //調用C#的ConnectWebsocket();
            dotnetHelper.invokeMethodAsync('ConnectWebsocket');
            //_self.ConnectWebsocket.call(_self);
        }, 5000);
    };
    gsocket.onmessage = function (e) {
        try {
            console.log('websocket onmessage');
            var msg = JSON.parse(e.data);
            //調用C#的onmessage();
            dotnetHelper.invokeMethodAsync('onmessage', msg);
            //_self.onmessage.call(_self, msg);
        } catch (e) {
            console.log(e);
            return;
        }
    };
    gsocket.onerror = function (e) {
        console.log('websocket error');
        gsocket = null;
        clearTimeout(gsocketTimeId);
        gsocketTimeId = setTimeout(function () {
            console.log('websocket onerror ConnectWebsocket');
            dotnetHelper.invokeMethodAsync('ConnectWebsocket');
            //_self.ConnectWebsocket.call(_self);
        }, 5000);
    };
}

 

  從JavaScript回調的onopen,onclose,onmessage實現

 [JSInvokable]
    public async Task onopen()
    {

        Console.WriteLine("websocket connect");
        wsConnectState = 1;
        await GetDesks();
        StateHasChanged();
    }
    [JSInvokable]
    public void onclose()
    {
        Console.WriteLine("websocket disconnect");
        wsConnectState = 0;
        StateHasChanged();
    }

    [JSInvokable]
    public async Task onmessage(object msgobjer)
    {
        try
        {
            var jsonDocument = JsonSerializer.Deserialize<object>(msgobjer.ToString());
            if (jsonDocument is JsonElement msg)
            {
                if (msg.TryGetProperty("type", out var element) && element.ValueKind == JsonValueKind.String)
                {
                    Console.WriteLine(element.ToString());
                    if (element.GetString() == "Sitdown")
                    {
                        Console.WriteLine(msg.GetProperty("msg").GetString());
                        var deskId = msg.GetProperty("deskId").GetInt32();
                        foreach (var desk in desks)
                        {
                            if (desk.Id.Equals(deskId))
                            {
                                var pos = msg.GetProperty("pos").GetInt32();
                                Console.WriteLine(pos);
                                var player = JsonSerializer.Deserialize<Player>(msg.GetProperty("player").ToString());
                                switch (pos)
                                {
                                    case 1:
                                        desk.player1 = player;
                                        break;
                                    case 2:
                                        desk.player2 = player;
                                        break;
                                    case 3:
                                        desk.player3 = player;
                                        break;

                                }
                                break;
                            }
                        }
                    }
                    else if (element.GetString() == "Standup")
                    {
                        Console.WriteLine(msg.GetProperty("msg").GetString());
                        var deskId = msg.GetProperty("deskId").GetInt32();
                        foreach (var desk in desks)
                        {
                            if (desk.Id.Equals(deskId))
                            {
                                var pos = msg.GetProperty("pos").GetInt32();
                                Console.WriteLine(pos);
                                switch (pos)
                                {
                                    case 1:
                                        desk.player1 = null;
                                        break;
                                    case 2:
                                        desk.player2 = null;
                                        break;
                                    case 3:
                                        desk.player3 = null;
                                        break;

                                }
                                break;
                            }
                        }
                    }
                    else if (element.GetString() == "GameStarted")
                    {
                        Console.WriteLine(msg.GetProperty("msg").GetString());
                        currentChannel.msgs.Insert(0, msg);
                    }
                    else if (element.GetString() == "GameOvered")
                    {
                        Console.WriteLine(msg.GetProperty("msg").GetString());
                        currentChannel.msgs.Insert(0, msg);
                    }
                    else if (element.GetString() == "GamePlay")
                    {

                        ddzid = msg.GetProperty("ddzid").GetString();
                        ddzdata = JsonSerializer.Deserialize<GameInfo>(msg.GetProperty("data").ToString());
                        Console.WriteLine(msg.GetProperty("data").ToString());
                        stage = ddzdata.stage;
                        selectedPokers = new int?[55];
                        if (playTips.Any())
                            playTips.RemoveRange(0, playTips.Count);
                        playTipsIndex = 0;

                        if (this.stage == "游戲結束")
                        {
                            foreach (var ddz in this.ddzdata.players)
                            {
                                if (ddz.id == player.Nick)
                                {
                                    this.player.Score += ddz.score;
                                    break;
                                }
                            }

                        }

                        if (this.ddzdata.operationTimeoutSeconds > 0 && this.ddzdata.operationTimeoutSeconds < 100)
                            await this.operationTimeoutTimer();
                    }
                    else if (element.GetString() == "chanmsg")
                    {
                        currentChannel.msgs.Insert(0, msg);
                        if (currentChannel.msgs.Count > 120)
                            currentChannel.msgs.RemoveRange(100, 20);
                    }

                }
                //Console.WriteLine("StateHasChanged");
                StateHasChanged();
                Console.WriteLine("onmessage_end");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"onmessage_ex_{ex.Message}_{msgobjer}");
        }

    }

  因為是回調函數所以這裡我們使用 StateHasChanged()來通知UI更新。

  在html5版中有使用setTimeout來刷新用戶的等待操作時間,我們可以通過一個折中方法實現

  

    private CancellationTokenSource timernnnxx { get; set; }

    //js setTimeout
    private async Task setTimeout(Func<Task> action, int time)
    {
        try
        {
            timernnnxx = new CancellationTokenSource();
            await Task.Delay(time, timernnnxx.Token);
            await action?.Invoke();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"setTimeout_{ex.Message}");
        }

    }
    private async Task operationTimeoutTimer()
    {
        Console.WriteLine("operationTimeoutTimer_" + this.ddzdata.operationTimeoutSeconds);
        if (timernnnxx != null)
        {
            timernnnxx.Cancel(false);
            Console.WriteLine("operationTimeoutTimer 取消");
        }
        this.ddzdata.operationTimeoutSeconds--;
        StateHasChanged();
        if (this.ddzdata.operationTimeoutSeconds > 0)
        {
            await setTimeout(this.operationTimeoutTimer, 1000);
        }
    }

  其他組件相關如數據綁定,事件處理,組件參數等等推薦直接看文檔也沒必要在複製一遍。

  完整實現下來感覺和寫MVC似的就是一把梭,各種C#語法,函數往上懟就行了,目前而言還是Web WebAssembly的功能有限,另外就是目前運行時比較大,掛在羊毛機上啟動下載都要一會才能下完,感受一下這個載入時間···


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 背景 筆者所在的公司正在進行微服務改造,這其中服務治理組件是必不可少的組件之一,在一番討論之後,最終決定放棄 Zookeeper 而採用 Consul 作為服務治理框架基礎組件。主要原因是 Consul 自帶健康檢查,通過該功能可以比較方便的監控應用的運行狀態,從而更好的運維整個系統。但在實際實施過 ...
  • 最近讀了一些文章,總結一下: 在1999年,當時微軟的windows系統運行的所有的應用程式都是有組件對象模型為根本基礎開發的,用VB來處理數據訪問和複雜的用戶界面,缺點是不能使用函數指針,因為當時的開發環境開發起來很不輕鬆,所有.NET的出現,變得更好了。 .NET 平臺由一個類框架和一個CLR的 ...
  • 數據的類型定義了存儲數據需要的記憶體大小及組成該類型的數據成員。類型還決定了對象在記憶體中的存儲位置——棧或堆。 類型被分為兩種:值類型和引用類型,這兩種類型的對象在記憶體中的存儲方式不同。 值類型只需要一段單獨的記憶體,用於存儲實際的數據。 引用類型需要兩段記憶體。 第一段存儲實際的數據,它總是位於堆中。 ...
  • 程式運行時,它的數據必須存儲在記憶體中。一個數據項需要多大的記憶體、存儲在記憶體中的什麼位置、以及如何存儲都依賴於該數據項的類型。 運行中的程式使用兩個記憶體區域來存儲數據:棧和堆。 棧 棧是一個記憶體數組,是一個 LIFO (Last In First Out,後進先出)的數據結構。棧存儲幾種類型的數據: ...
  • 上一篇(地址: "https://www.vinanysoft.com/c sharp basics/data types/fundamental numeric types/" )只介紹了基本數值類型,本篇將介紹其他的一些類型: 、`char string`。 布爾類型( ) 關鍵字是 的別名。 ...
  • 在之前的文章中(地址: "https://www.vinanysoft.com/c sharp basics/introducing/" ),以 HelloWorld 程式為基礎,介紹 C 語言、它的結構、基本語法以及如何編寫最簡單的程式有了初步理解。 接下來介紹基本的 C 類型,繼續鞏固 C 的基 ...
  • 使用 Ocelot 匹配路由的方法匹配路由 Intro 之前我們在 Ocelot 網關的基礎上 "自定義了一個認證授權的 Ocelot 中間件" ,根據請求的路徑和 Method 進行匹配,找到對應的許可權配置,並判斷是否可以擁有訪問資源的角色,如果沒有則返回 401/403,如果有許可權則轉發到下游服 ...
  • 本系列已介紹一款國內開源C# Winform控制項庫,大家如有比較好的開源C# Winform控制項庫,歡迎向Dotnet9推薦,您可在本文下方留言,謝謝您對dotnet的關註和支持,讓我們期待dotnet更好的明天,以下是Dotnet9已完成的1篇開源C# Winform控制項庫推薦文章: 1、 《Do ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...