Azure SignalR Service を利用して,ブラウザ上でチャットのサンプルを動作させます.
SignalR 概要
- https://docs.microsoft.com/ja-jp/aspnet/core/signalr/introduction?view=aspnetcore-5.0
- ブラウザなどからリアルタイム通信を行うためのライブラリ
- 内部的にはWebSocketやポーリングなどを利用して双方向での通信を実現している
- 利用者は内部の通信処理を意識することなくブラウザにリアルタイム通信機能を追加できる
- 自前実装には別途サーバー側の実装も必要
Azure SignalR Service 概要
- https://azure.microsoft.com/ja-jp/services/signalr-service/#overview
- ブラウザでのリアルタイム通信を実現するためのサーバー側機能を構築してくれる
- Azure Function と組み合わせることでブラウザからの SignalR サーバーへの接続とリアルタイム通信を追加可能
チャットアプリのサンプル実行
- 利用した Function サンプルプロジェクト
- https://docs.microsoft.com/ja-jp/azure/azure-signalr/signalr-quickstart-azure-functions-csharp
Azure SignalR Service 設定
Azure ポータルから
SignalR Service
を作成Service mode
をServerless
にして作成作成後
Keys
のConnection string
を控えておく
Azure Function 設定
- Azure ポータルから
Function App
を作成


Function 作成
開発環境
- https://docs.microsoft.com/ja-jp/azure/azure-signalr/signalr-quickstart-azure-functions-csharp
上記のプロジェクトをCloneして, C# 用の Function プロジェクト
signalr-service-quickstart-serverless-chat\src\chat\csharp\FunctionApp.sln
を Visual Studio で開くAzure 環境にアップロードするため,パッケージのバージョンを更新
プロジェクトを右クリックから
Manage NuGet Packages...
を開き以下を設定Microsoft.NET.Sdk.Function
を3.0.13
に更新Microsoft.Azure.WebJobs.Extensions.SignalRService
を1.3.0
に更新Microsoft.Azure.WebJobs.Extensions
の4.0.1
を追加Microsoft.Azure.WebJobs.Extensions.Http
の3.0.12
を追加



Function.cs
内では SignalR 接続処理を行うnegotiate
と送受信データを処理するmessages
が実装されています
サンプルプロジェクトのローカル実行
local.settings.sample.json
をlocal.settings.json
に名前変更local.settings.json
のAzureSignalRConnectionString
に Azure SignalR Service 作成時に控えておいたConnection string
を入力

- プロジェクト実行後,以下のブラウザにアクセスしチャット機能を確認
- https://azure-samples.github.io/signalr-service-quickstart-serverless-chat/demo/chat-v2/
- Azure Function 接続URLの指定は,ローカル実行時にはデフォルト(
http://localhost:7071
)を利用

- 複数のブラウザでアクセスすることでチャット機能を確認できる

サンプルプロジェクトの Azure 実行
- 作成した Function プロジェクトを Azure にアップロード
- プロジェクト右クリックから
Publish
を選択

- アップロード先に Azure を選択し,アップロードする Azure Function を選択


アップロード先の Azure Function を指定できたら,
Publish
からアップロードを行うアップロードに成功すると Azure ポータルの Azure Function の関数画面に
message
とnegotiate
が確認できる

- 作成した SignalR Service に接続するために Azure Function に接続文字列を設定する
Configuration
のApplication settings
からNew application setting
を行う- Name に
AzureSignalRConnectionString
と Value に SignalR Service 作成時に控えたConnection string
を入力


- 外部からの接続を許可するために
CORS
のEnable Access-Control-Allow-Credentials
にチェック https://azure-samples.github.io
を設定

- 以下のブラウザにアクセスしチャット機能を確認
- https://azure-samples.github.io/signalr-service-quickstart-serverless-chat/demo/chat-v2/
- Azure Function 接続URLの指定は,設定した Azure Function の URL を利用

- 複数のブラウザでアクセスすることでチャット機能を確認できる
まとめ
- まずはブラウザ間でSignalRを利用したチャットアプリが動くことが確認できた.