Skip to content

Instantly share code, notes, and snippets.

@RobertBouillon
Created January 26, 2021 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobertBouillon/8cf121c329620cc2e396b3b772041bfe to your computer and use it in GitHub Desktop.
Save RobertBouillon/8cf121c329620cc2e396b3b772041bfe to your computer and use it in GitHub Desktop.
Blazor IPC for Chromely (Host C#)
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