-
-
Save RobertBouillon/8cf121c329620cc2e396b3b772041bfe to your computer and use it in GitHub Desktop.
Blazor IPC for Chromely (Host C#)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Chromely.Core.Network; | |
using System; | |
using System.Collections.Generic; | |
namespace TempusChromely | |
{ | |
[ControllerProperty(Name = "MessageHandler")] | |
public class MessageHandler : ChromelyController | |
{ | |
private static Dictionary<String, Action<String>> _commands = new Dictionary<string, Action<string>>(); | |
private static Dictionary<String, Func<String, String>> _requests = new Dictionary<string, Func<string, string>>(); | |
public static void RegisterCommand(string type, Action<string> handler) => _commands.Add(type, handler); | |
public static void RegisterRequest(string type, Func<string,string> handler) => _requests.Add(type, handler); | |
public MessageHandler() | |
{ | |
RegisterRequest("/host/request", HandleRequest); | |
RegisterRequest("/host/command", HandleCommand); | |
} | |
private IChromelyResponse HandleRequest(IChromelyRequest request) | |
{ | |
var type = request.Parameters["type"]; | |
if (!_requests.TryGetValue(type, out var handler)) | |
throw new Exception($"No handlers registered for '{type}' requests"); | |
return new ChromelyResponse(request.Id) { Data = handler(request.PostData.ToString()) }; | |
} | |
//Don't use the command functionality offered by Chromely. Commands only allow parameters and we want to be able to post data. | |
private IChromelyResponse HandleCommand(IChromelyRequest request) | |
{ | |
var type = request.Parameters["type"]; | |
if (!_commands.TryGetValue(type, out var handler)) | |
throw new Exception($"No handlers registered for '{type}' commands"); | |
handler(request.PostData.ToString()); | |
return new ChromelyResponse(request.Id); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment