【问题标题】:Get data from tcp listener callback in the main thread从主线程中的 tcp listener 回调中获取数据
【发布时间】:2023-03-08 21:02:02
【问题描述】:

我创建了一个透明代理来修复传入的数据,但我希望在主线程(我打开了套接字)中拥有来自侦听回调的所有数据。在 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 执行程序)中获取 OnReceiveResponse 的所有数据。我为一个呼叫做这样的代理 - 所以数据不超过 1kB。

【问题讨论】:

  • 您能否提供更多详细信息?显示连接初始化和管理的代码,每个人都需要知道你在主线程中处理数据的代码,你要存储多少?

标签: c# multithreading tcp proxy server


【解决方案1】:

可能你适合生产者/消费者模式,尝试使用 BlockingCollection 它支持“同时从多个线程添加和获取项目”

(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()

【讨论】:

  • 你成就了我的一天!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 1970-01-01
  • 2018-01-13
  • 1970-01-01
  • 2020-05-28
  • 2014-06-28
相关资源
最近更新 更多