Advertisement
touhid_xml

NATIVE MESSAGING HOST

Jan 29th, 2016
380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.03 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using Newtonsoft.Json;
  4. using Newtonsoft.Json.Linq;
  5.  
  6. namespace NativeMessagingHost
  7. {
  8.    class Program
  9.    {
  10.       public static void Main(string[] args)
  11.       {
  12.          JObject data;
  13.          while ((data = Read()) != null)
  14.          {
  15.             var processed = ProcessMessage(data);
  16.             Write(processed);
  17.             if (processed == "exit")
  18.             {
  19.                return;
  20.             }
  21.          }
  22.       }
  23.  
  24.       public static string ProcessMessage(JObject data)
  25.       {
  26.          var message = data["message"].Value<string>();
  27.          switch (message)
  28.          {
  29.             case "test":
  30.                return "testing!";
  31.             case "exit":
  32.                return "exit";
  33.             default:
  34.                return "echo: " + message;
  35.          }
  36.       }
  37.  
  38.       public static JObject Read()
  39.       {
  40.          var stdin = Console.OpenStandardInput();
  41.          var length = 0;
  42.  
  43.          var lengthBytes = new byte[4];
  44.          stdin.Read(lengthBytes, 0, 4);
  45.          length = BitConverter.ToInt32(lengthBytes, 0);
  46.  
  47.          var buffer = new char[length];
  48.          using (var reader = new StreamReader(stdin))
  49.          {
  50.             while (reader.Peek() >= 0)
  51.             {
  52.                reader.Read(buffer, 0, buffer.Length);
  53.             }
  54.          }
  55.  
  56.          return (JObject)JsonConvert.DeserializeObject<JObject>(new string(buffer))["data"];
  57.       }
  58.  
  59.       public static void Write(JToken data)
  60.       {
  61.          var json = new JObject();
  62.          json["data"] = data;
  63.  
  64.          var bytes = System.Text.Encoding.UTF8.GetBytes(json.ToString(Formatting.None));
  65.  
  66.          var stdout = Console.OpenStandardOutput();
  67.          stdout.WriteByte((byte)((bytes.Length >> 0) & 0xFF));
  68.          stdout.WriteByte((byte)((bytes.Length >> 8) & 0xFF));
  69.          stdout.WriteByte((byte)((bytes.Length >> 16) & 0xFF));
  70.          stdout.WriteByte((byte)((bytes.Length >> 24) & 0xFF));
  71.          stdout.Write(bytes, 0, bytes.Length);
  72.          stdout.Flush();
  73.       }
  74.    }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement