嗯...有可能是更好的方法,但一个简单的方法可以在你的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功能,您可以读取发布数据或发送的东西回来。
获取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();
只是一些简单的头脑风暴,期待更好的想法:)
setInterval(poll,1000); < - 这不完全是轮询:)轮询是当你发送一个请求,它将不会返回一个响应,直到它是必要的,但问题是好的:) – povilasp
改变它为中性setInterval(getCommand,1000),@povilasp。欢呼声:) – cviejo
你有可能给我发送一些例子吗?请,因为我对此很新。 –