gpt4 book ai didi

C# native 主机与 Chrome native 消息传递

转载 作者:IT王子 更新时间:2023-10-29 04:30:30 24 4
gpt4 key购买 nike

我今天花了几个小时研究如何让 Chrome 原生消息与 C# 原生主机一起工作。从概念上讲,它非常简单,但在这些其他问题的帮助下(部分)我解决了一些问题:

Native Messaging Chrome
Native messaging from chrome extension to native host written in C#
Very Slow to pass "large" amount of data from Chrome Extension to Host (written in C#)

我的解决方案发布在下面。

最佳答案

假设 list 设置正确,下面是使用“端口”方法与 C# 主机通信的完整示例:

using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace NativeMessagingHost
{
class Program
{
public static void Main(string[] args)
{
JObject data;
while ((data = Read()) != null)
{
var processed = ProcessMessage(data);
Write(processed);
if (processed == "exit")
{
return;
}
}
}

public static string ProcessMessage(JObject data)
{
var message = data["text"].Value<string>();
switch (message)
{
case "test":
return "testing!";
case "exit":
return "exit";
default:
return "echo: " + message;
}
}

public static JObject Read()
{
var stdin = Console.OpenStandardInput();
var length = 0;

var lengthBytes = new byte[4];
stdin.Read(lengthBytes, 0, 4);
length = BitConverter.ToInt32(lengthBytes, 0);

var buffer = new char[length];
using (var reader = new StreamReader(stdin))
{
while (reader.Peek() >= 0)
{
reader.Read(buffer, 0, buffer.Length);
}
}

return (JObject)JsonConvert.DeserializeObject<JObject>(new string(buffer));
}

public static void Write(JToken data)
{
var json = new JObject();
json["data"] = data;

var bytes = System.Text.Encoding.UTF8.GetBytes(json.ToString(Formatting.None));

var stdout = Console.OpenStandardOutput();
stdout.WriteByte((byte)((bytes.Length >> 0) & 0xFF));
stdout.WriteByte((byte)((bytes.Length >> 8) & 0xFF));
stdout.WriteByte((byte)((bytes.Length >> 16) & 0xFF));
stdout.WriteByte((byte)((bytes.Length >> 24) & 0xFF));
stdout.Write(bytes, 0, bytes.Length);
stdout.Flush();
}
}
}

如果您不需要主动与主机通信,使用runtime.sendNativeMessage 就可以了。为防止主机挂起,只需删除 while 循环并执行一次读/写。

为了对此进行测试,我在这里使用了 Google 提供的示例项目:https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/docs/examples/api/nativeMessaging

注意:我使用 Json.NET 来简化 json 序列化/反序列化过程。

希望对大家有所帮助!

关于C# native 主机与 Chrome native 消息传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30880709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com