之前群里大神發了一個 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
服務。
預設已註入了HttpClient,IJSRuntime,NavigationManager,具體可以看官方文檔介紹。
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的功能有限,另外就是目前運行時比較大,掛在羊毛機上啟動下載都要一會才能下完,感受一下這個載入時間···