1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[ASP.NET Core SignalR] ハブからアプケーションデータを操作する

Posted at

目的

以下の記事でASP.NET Core SignalRを使ってチュートリアル通りにWebアプリケーションを作成したが、サーバ側の処理がハブで完結しており、他クラス間の参照方法が不明であったため調査した。
https://qiita.com/takmot/items/7fc13b50a3c8d0f6d2aa

private int state = 0;  // サーバ状態

このようなサーバ側で管理している状態をクライアントに送信したい

ハブでの状態管理について

以下のようにできないか。

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace SignalRChat.Hubs
{
    // ハブ
    public class ChatHub : Hub
    {
        private int state = 0;  // サーバ状態

        public async Task getState()
        {
            await Clients.Caller.SendAsync("getState", state.ToString());
        }
    }
}

以下のように公式に記載があり、ハブクラスにサーバの状態等を保持して管理することはできない。
https://docs.microsoft.com/ja-jp/aspnet/core/signalr/hubs?view=aspnetcore-3.1
image.png

状態管理用のクラスから取得する

以下の方法でサーバ側で管理している状態をクライアントに送信することができた

  • 別途状態管理用にクラスを作成する
namespace SignalRChat
{
    // 状態管理用クラス
    public class app
    {
        private int state = 0;  // サーバ状態
        
        public int getState()
        {
            return state;
        }
    }
}
  • ハブクラスでappクラスからサーバ状態を取得する
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace SignalRChat.Hubs
{
    // ハブ
    public class ChatHub : Hub
    {
        private readonly app _app;

        public ChatHub(app App)
        {
            _app = App;  // コンストラクタでappのコンテキストを取得
        }
        public async Task getState()
        {
            int state = _app.getState();    // appからサーバ状態取得
            await Clients.Caller.SendAsync("getState", state.ToString());   // 呼び元にstateを返す
        }
    }
}
  • startup.csを変更
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddSignalR();
            services.AddSingleton<app>(); // 追加
        }

以下、参考にした公式のサンプル
https://github.com/aspnet/SignalR-samples/tree/master/StockTickR/StockTickRApp

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?