我已经创建了一个透明的代理来修复传入的数据,但是我希望在主线程(打开套接字的地方)中拥有来自侦听回调的所有数据。在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();
}
}
}因此,我主要需要在主线程( OnReceiveResponse executor)中获取OnReceiveResponse中的所有数据。我为一个呼叫做这样一个代理-所以数据不超过1kB。
发布于 2016-02-20 10:33:24
可能您适合生产者/使用者模式,尝试使用BlockingCollection it支持“从多个线程中并发添加和获取项”。
(https://msdn.microsoft.com/en-us/library/dd997371(v=vs.110).aspx是这样的:
BlockingCollection<Data> dataItems = new BlockingCollection<Data>(100);在您的dataReceiver处理程序中
dataItems.Add(data);在您的主线程使用者中:
data = dataItems.Take();用睡眠替换无穷大循环到Console.Readkey()也更好
https://stackoverflow.com/questions/35521702
复制相似问题