嗯...可能有更好的方法,但一种简单的方法可能是在您的 c# 应用程序中打开一个HttpListener并从扩展程序中与它进行通信,如下所示:
var listener = "http://localhost:60024/";
function getCommand(){
var postData = {
"action": "getCommand"
};
$.post( listener, postData, function(response){
//Parse response and do whatever c# wants
});
}
function send(data){
var postData = {
"action" : "send",
"data": data
};
$.post(listener, postData);
}
setInterval(getCommand, 1000);
在示例中,我使用了 jQuery.post,它可以添加到扩展上下文中,但如果您更喜欢它,可以使用 XMLHttpRequest。在 c# 方面:
using System;
using System.Net;
namespace HttpListenerTEst
{
class Program
{
private static HttpListener _listener;
static void Main(string[] args)
{
_listener = new HttpListener();
_listener.Prefixes.Add("http://localhost:60024/");
_listener.Start();
_listener.BeginGetContext(new AsyncCallback(Program.ProcessRequest), null);
Console.ReadLine();
}
static void ProcessRequest(IAsyncResult result)
{
HttpListenerContext context = _listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
//Answer getCommand/get post data/do whatever
_listener.BeginGetContext(new AsyncCallback(Program.ProcessRequest), null);
}
}
}
在 ProcessRequest 函数中,您可以读取发布数据或发回某些内容。
获取帖子数据:
string postData;
using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
{
postData = reader.ReadToEnd();
//use your favourite json parser here
}
并通过以下方式发回一些东西:
string responseString = "This could be json to be parsed by the extension";
HttpListenerResponse response = context.Response;
response.ContentType = "text/html";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
只是一些快速的头脑风暴,期待更好的想法:)