以前羣裏大神發了一個 html5+ .NETCore的鬥地主,恰好在看Blazor WebAssembly 就嘗試重寫試試。javascript
還有就是有些標題黨了,由於文章裏幾乎沒有鬥地主的相關實現:),這裏主要介紹一些Blazor前端的一些方法實現而鬥地主的實現總結來講就是獲取數據綁定UI,語法上基本就是Razor,頁面上的注入語法等不在重複介紹,完整實現能夠查看github:https://github.com/saber-wang/FightLandlord/tree/master/src/BetGame.DDZ.WasmClient,在線演示:http://39.106.159.180:31000/html
另外強調一下Blazor WebAssembly 是純前端框架,全部相關組件等都會下載到瀏覽器運行,要和MVC、Razor Pages等區分開來前端
當前是基於NetCore3.1和Blazor WebAssembly 3.1.0-preview4。html5
Blazor WebAssembly默認是沒有安裝的,在命令行執行下邊的命令安裝Blazor WebAssembly模板。java
dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.1.0-preview4.19579.2
選擇Blazor應用,跟着往下就會看到Blazor WebAssembly App模板,若是看不到就在ASP.NET Core3.0和3.1之間切換一下。git
新建後項目結構以下。github
一眼看過去,大致和Razor Pages 差很少。Program.cs也和ASP.NET Core差很少,區別是返回了一個IWebAssemblyHostBuilder。web
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,並指定了啓動組件json
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
服務。api
默認已注入了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的功能有限,另外就是目前運行時比較大,掛在羊毛機上啓動下載都要一會才能下完,感覺一下這個加載時間···