简体   繁体   English

C# TcpClient Send 方法有时需要太长时间

[英]C# TcpClient Send method takes too long sometimes

If I'm sending data too fast the .Send method takes really long.如果我发送数据太快,.Send 方法需要很长时间。 I'm talking up to 20 ms here, which is not an option for my application.我在这里谈论最多 20 毫秒,这不是我的应用程序的选项。 What causes this?这是什么原因造成的? And how can I avoid it?我怎样才能避免它?

Some test code that reproduces the problem: test client:一些重现问题的测试代码:测试客户端:

            var lol = new TcpClient();
        lol.Connect(IPAddress.Parse("123.123.123.123"), 1234);

        while (true)
        {
            var watchy = Stopwatch.StartNew();
            lol.Client.Send(new byte[] {123, 34, 34, 98, 45, 87, 34, 78, 45, 76, 45, 23, 154, 146, 1, 1, 1, 11, 66}); // random test data
            watchy.Stop();

            Console.WriteLine(watchy.Elapsed.TotalMilliseconds);

            if (watchy.Elapsed.TotalMilliseconds > 1)
                Console.ReadLine();
        }

test server:测试服务器:

            var listener = new TcpListener(IPAddress.Any, 1234);
        listener.Start();
        var clients = new List<TcpClient>();

        while (true)
        {
            if (listener.Pending())
            {
                clients.Add(listener.AcceptTcpClient());
                Console.WriteLine("client connected!");
            }

            foreach (var tcpClient in clients)
            {
                var data = new byte[tcpClient.Available];
                tcpClient.Client.Receive(data);
                Console.WriteLine(string.Join(" ", data));
            }
        }

I think the receiver can't process the data fast enough.我认为接收器不能足够快地处理数据。 But how can I check if I'm currerntly able to send data without the delay?但是我如何检查我当前是否能够无延迟地发送数据? I'm sending to multiple clients, which means that other clients will experience lag because one client wasn't able to process the data fast enough我正在发送给多个客户端,这意味着其他客户端会遇到延迟,因为一个客户端无法足够快地处理数据

我通过将 .Blocking of the socket 设置为 false 解决了这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM