我正在尝试编写一个集成测试来证明如果尝试连接到服务器的速度太慢,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,但看不到任何明显的方法来注入(inject)一些必须在客户端连接建立之前完成的服务器端逻辑。
有什么方法可以让我使用 TcpClient
和 Socket
伪造一个慢速服务器/连接?
最佳答案
Visual Studio 自带网络模拟器(http://msdn.microsoft.com/en-us/library/dd505008.aspx)
关于.net - 使用 TcpClient 和 Socket 伪造慢速连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11501337/