【问题标题】:Communicate between Native Messaging Host and C# app在本机消息传递主机和 C# 应用程序之间进行通信
【发布时间】:2015-07-01 23:47:20
【问题描述】:

我有一个 chrome 扩展程序,可以与我在 C# 中创建的本机消息传递主机通信。

但是,如何在 Native Messaging Host 和 C# 应用程序之间进行通信。我认为它将通过 Native Messaging Host 输入/输出流,但我无法找到如何做到这一点。

【问题讨论】:

标签: c# google-chrome-extension chrome-native-messaging


【解决方案1】:

我找不到使用 Process.StandardInput 的方法,因为 chrome 启动了本机消息传递主机。

相反,我使用了 WCF。代码如下:

    private static object SyncRoot = new object();
    static string returnValue = null;

    [ServiceContract]
    public interface IGetChromeString
    {
        [OperationContract]
        string GetString(string value);
    }

    public class CGetChromeString : IGetChromeString
    {
        public string GetString(string value)
        {
            OpenStandardStreamOut(value);
            // Wait until OpenStandardStreamIn() sets returnValue in the Main Thread
            lock (SyncRoot)
            {
                Monitor.Wait(SyncRoot);
            }
            return returnValue;
        }
    }

    static void Main(string[] args)
    {
        using (ServiceHost host = new ServiceHost(typeof(CGetChromeString), new Uri[] { new Uri("net.pipe://localhost") }))
        {
            host.AddServiceEndpoint(typeof(IGetChromeString), new NetNamedPipeBinding(), "PipeReverse");

            host.Open();
            while (returnValue != "")
            {
                returnValue = OpenStandardStreamIn();
                // returnValue has been set, GetUrl can resume.
                lock (SyncRoot)
                {
                    Monitor.Pulse(SyncRoot);
                }
            }

            host.Close();
        }
    }

    static string OpenStandardStreamIn()
    {
        Stream stdin = Console.OpenStandardInput();
        byte[] bytes = new byte[4];
        stdin.Read(bytes, 0, 4);
        int length = 0;

        length = System.BitConverter.ToInt32(bytes, 0);

        string input = "";
        for (int i = 0; i < length; i++)
        {
            input += (char)stdin.ReadByte();
        }
        return input;
    }

    static void OpenStandardStreamOut(string stringData)
    {
        string msgdata = "{\"text\":\"" + stringData + "\"}";
        int DataLength = msgdata.Length;
        Stream stdout = Console.OpenStandardOutput();
        stdout.WriteByte((byte)((DataLength >> 0) & 0xFF));
        stdout.WriteByte((byte)((DataLength >> 8) & 0xFF));
        stdout.WriteByte((byte)((DataLength >> 16) & 0xFF));
        stdout.WriteByte((byte)((DataLength >> 24) & 0xFF));
        Console.Write(msgdata);
    }

【讨论】:

    猜你喜欢
    • 2016-05-20
    • 2019-05-08
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 2011-05-17
    相关资源
    最近更新 更多