首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从主线程中的tcp侦听器回调中获取数据

从主线程中的tcp侦听器回调中获取数据
EN

Stack Overflow用户
提问于 2016-02-20 10:06:15
回答 1查看 488关注 0票数 0

我已经创建了一个透明的代理来修复传入的数据,但是我希望在主线程(打开套接字的地方)中拥有来自侦听回调的所有数据。在C#中做这件事的最好方法是什么?

我正在使用库TrotiNet加上一些重写逻辑-修复响应头。简单的代码如下所示

代码语言:javascript
复制
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。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-20 10:33:24

可能您适合生产者/使用者模式,尝试使用BlockingCollection it支持“从多个线程中并发添加和获取项”。

(https://msdn.microsoft.com/en-us/library/dd997371(v=vs.110).aspx是这样的:

代码语言:javascript
复制
BlockingCollection<Data> dataItems = new BlockingCollection<Data>(100);

在您的dataReceiver处理程序中

代码语言:javascript
复制
dataItems.Add(data);

在您的主线程使用者中:

代码语言:javascript
复制
data = dataItems.Take();

用睡眠替换无穷大循环到Console.Readkey()也更好

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35521702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档