【问题标题】:Faking a slow connect with TcpClient and Socket使用 TcpClient 和 Socket 伪造慢速连接
【发布时间】:2012-07-16 09:17:14
【问题描述】:

我正在尝试编写一个集成测试来证明如果连接到服务器的尝试太慢,TCP 客户端将正确超时。我有一个FakeServer 类,它打开一个Socket 并监听传入的连接:

public sealed class FakeServer : IDisposable
{
    ...

    public TimeSpan ConnectDelay
    {
        get; set;
    }

    public void Start()
    {
        this.CreateSocket();
        this.socket.Listen(int.MaxValue);

        this.socket.BeginAccept(this.OnSocketAccepted, null);
    }

    private void CreateSocket()
    {
        var ip = new IPAddress(new byte[] { 0, 0, 0, 0 });
        var endPoint = new IPEndPoint(ip, Port);
        this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        this.socket.Bind(endPoint);
    }

    private void OnSocketAccepted(IAsyncResult asyncResult)
    {
        Thread.Sleep(this.connectDelay);
        this.clientSocket = this.socket.EndAccept(asyncResult);
    }
}

请注意我尝试通过调用Thread.Sleep() 来延迟连接成功。不幸的是,这不起作用:

[Fact]
public void tcp_client_test()
{
    this.fakeServer.ConnectDelay = TimeSpan.FromSeconds(20);
    var tcpClient = new TcpClient();
    tcpClient.Connect("localhost", FakeServer.Port);
}

在上面的测试中,对tcpClient.Connect() 的调用立即成功,甚至在服务器端OnSocketAccepted 方法被调用之前。我查看了 API,但看不到任何明显的方法可以注入一些必须在来自客户端的连接建立之前完成的服务器端逻辑。

我有什么方法可以使用TcpClientSocket 来伪造慢速服务器/连接?

【问题讨论】:

  • +1 用于实际测试不良/慢速连接,这与其他无知世界不同 :)
  • 您可以使用像 NetLimiter 这样的工具来限制连接。可惜不是免费的。
  • SO/SE 网络上有很多问题都涵盖了这个主题。许多特定于浏览器或特定操作系统(OS X 至少有 2 个),但 this onethis onethis one 应该有您可以使用的解决方案。
  • 这里也有一些通用的解决方案:webmasters.stackexchange.com/questions/861/…
  • 我不喜欢网络工具,因为它是作为集成测试运行的。

标签: .net sockets tcp integration-testing


【解决方案1】:

Visual Studio 自带网络模拟器(http://msdn.microsoft.com/en-us/library/dd505008.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 2012-03-22
    • 2013-05-15
    相关资源
    最近更新 更多