【问题标题】:sending tcp data every 10 seconds - but actually send each 20 seconds每 10 秒发送一次 tcp 数据 - 但实际上每 20 秒发送一次
【发布时间】:2020-09-05 23:14:01
【问题描述】:

我编写了一些更简单的代码,将字节数组数据发送到某个 tcp 套接字。 我以前做过很多次 - 但由于某种原因,这没有按我的预期工作。

我在日志中看到我的主线程假设要休眠 10 秒 - 实际上它在发送下一个包之前休眠了 24 秒

我无法对此进行合理的逻辑解释。 还尝试从不同的线程运行主循环(和发送)......结果相同

代码:

public class Program
{
    static List<byte[]> _dataToSend = new List<byte[]>();
    static TcpClient _tcpClient = new TcpClient();


    static void Main(string[] args)
    {
        //
        //  init the TCP client => connect successful 

        //  add data to the _dataToSend 

        foreach (byte[] item in _dataToSend)
        {

            _tcpClient.Client.Send(item);

            Thread.Sleep(10000);       // 10 second
        }
    }
}

【问题讨论】:

  • 您在发送该项目后 睡了 10 秒。寄出物品需要多长时间?
  • 是的。我会在这里开始研究异步(浪费一个线程来休眠 10 秒 - 哎哟)。那么你基本上可以发送数据,等待然后等待看看最后一次发送是如何完成的。
  • 发送需要 10-20 毫秒
  • 我不想在这种情况下使用异步

标签: c#


【解决方案1】:

尝试在TcpClient 上禁用延迟:

_tcpClient.NoDelay = true;

【讨论】:

    【解决方案2】:

    正如其他人所说,发送数据可能需要一些额外的时间。所以,你可以做的是计算你需要等待的剩余时间跨度。

    试试这样的:

    var sw = new Stopwatch();
    
    foreach (byte[] item in _dataToSend)
    {
        sw.Restart();
    
        _tcpClient.Client.Send(item);
    
        int remainingMilliseconds = (int)(10000 - sw.ElapsedMilliseconds);
        if (remainingMilliseconds > 0) Thread.Sleep(remainingMilliseconds);
    }
    

    这样,如果发送需要 5 秒,例如,您只需再等待 5 秒。如果发送时间超过 10 秒,则根本无需等待。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多