嗯...可能有更好的方法,但一个简单的方法是在你的c#应用程序中打开一个HttpListener,并像这样从扩展程序与其通信:
var listener = "http://localhost:60024/";
function getCommand(){
var postData = {
"action": "getCommand"
};
$.post( listener, postData, function(response){
});
}
function send(data){
var postData = {
"action" : "send",
"data": data
};
$.post(listener, postData);
}
setInterval(getCommand, 1000);
在这个例子中,我使用的是jQuery.post,它可以添加到扩展上下文中,但如果你更喜欢,你也可以使用XMLHttpRequest。在C#方面:
在我的示例中,我使用了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;
_listener.BeginGetContext(new AsyncCallback(Program.ProcessRequest), null);
}
}
}
在 ProcessRequest 函数中,您可以读取 POST 数据或发送回应。
读取 POST 数据:
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();
只是一些快速的头脑风暴,期待更好的想法 :)