我已经创建了一个透明的代理来修复传入的数据,但是我希望在主线程(我已经打开套接字的地方)中收听来自监听回调的所有数据。在C#中最好的方法是什么?
我正在使用库TrotiNet加上一些重写逻辑 - 修复响应头。简单的代码 - 如下
using System;
using TrotiNet;
namespace TrotiNet.Example
{
public class TransparentProxy : ProxyLogic
{
public TransparentProxy(HttpSocket clientSocket)
: base(clientSocket) { }
static new public TransparentProxy CreateProxy(HttpSocket clientSocket)
{
return new TransparentProxy(clientSocket);
}
protected override void OnReceiveRequest()
{
Console.WriteLine("-> " + RequestLine + " from HTTP referer " +
RequestHeaders.Referer);
}
protected override void OnReceiveResponse()
{
Console.WriteLine("<- " + ResponseStatusLine +
" with HTTP Content-Length: " +
(ResponseHeaders.ContentLength ?? 0));
}
}
public static class Example
{
public static void Main()
{
int port = 12345;
bool bUseIPv6 = false;
var Server = new TcpServer(port, bUseIPv6);
Server.Start(TransparentProxy.CreateProxy);
Server.InitListenFinished.WaitOne();
if (Server.InitListenException != null)
throw Server.InitListenException;
while (true)
{
//need to get the response data here
System.Threading.Thread.Sleep(1000);
}
//Server.Stop();
}
}
}
所以主要是,我需要在主线程(Example.Main executor)中获取OnReceiveResponse的所有数据。我为一个电话做了这样的代理 - 所以数据不超过1kB。
答案 0 :(得分:1)
可能你适合生产者/消费者模式,尝试使用它支持的BlockingCollection&#34;从多个线程同时添加和获取项目&#34;
(https://msdn.microsoft.com/en-us/library/dd997371(v=vs.110).aspx)喜欢这样:
.on("mousemove", function(d, i){
piesvg.select(".text-tooltip")
.attr("fill", colorspie(i))
.text(d.data.domain + ":" + parseInt(d.data.value * 20));
});
在dataReceiver处理程序中执行
BlockingCollection<Data> dataItems = new BlockingCollection<Data>(100);
主线程消费者中的:
dataItems.Add(data);
最好将睡眠中的无限循环替换为Console.Readkey()